输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
说明:二叉树A中可能含有相同的节点,因此HasSubtree应该进行一次根节点的递归。searchTree是以pRoot1为根节点去依次对比pRoot2的节点
function HasSubtree(pRoot1, pRoot2)
{
if(pRoot2 === null || pRoot1 === null){
return false;
}
// 以A树的每个节点为根节点,依次去对比B树的节点
if(pRoot1 !== null){
let res1 = searchTree(pRoot1, pRoot2);
let res2 = HasSubtree(pRoot1.left , pRoot2);
let res3 = HasSubtree(pRoot1.right , pRoot2);
return res1 || res2 || res3;
}
}
function searchTree(pRoot1, pRoot2){
if(pRoot2 === null){
return true;
}
if(pRoot1 === null && pRoot2 !== null){
return false;
}
if(pRoot1.val === pRoot2.val){
let left = searchTree(pRoot1.left , pRoot2.left);
let right = searchTree(pRoot1.right , pRoot2.right);
return left && right;
}else {
return false;
}
}