上题目:
输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
例如: 给定的树 A:
3
/
4 5
/
1 2
给定的树 B:
4 / 1 返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。
示例 1:
输入:A = [1,2,3], B = [3,1] 输出:false 示例 2:
输入:A = [3,4,5,1,2], B = [4,1] 输出:true 限制:
0 <= 节点个数 <= 10000
解题:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} A
* @param {TreeNode} B
* @return {boolean}
*/
var isSubStructure = function(A, B) {
if (!A || !B) return false
const roots = []
const findRoots = (originNode, searchNode, roots) => {
if (originNode) {
if (originNode.val === searchNode.val) {
roots.push(originNode)
}
findRoots(originNode.left, searchNode, roots)
findRoots(originNode.right, searchNode, roots)
}
}
const checkSame = (originNode, searchNode) => {
if (!originNode && !searchNode) {
return true
} else if (originNode && searchNode) {
if (originNode.val !== searchNode.val) {
return false
} else {
return checkSame(originNode.left, searchNode.left) && checkSame(originNode.right, searchNode.right)
}
} else if (originNode && !searchNode) {
return true
} else {
return false
}
}
findRoots(A, B, roots)
return !roots.length
? false
: roots.some(root => checkSame(root, B))
};