题目描述:
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路:
1、当Tree1和Tree2都不为零的时候,才进行比较。否则直接返回false
2、如果在Tree1中找到了和Tree2的根节点值相同的点,则以这个节点为起点,判断是否包含Tree2;如果没找到,则直接返回false。
3、定义一个方法,将上述Tree1中的那个节点和Tree2作为参数,二者值相等,回调继续比较左子树和右子树,直到二者的值出现不等,或者当Tree1比Tree2先遍历完时,返回false,否则返回true。
代码实现:
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function HasSubtree(pRoot1, pRoot2)
{
// write code here
var result = false;
if (pRoot1!==null && pRoot2!==null){
if (pRoot1.val === pRoot2.val){
result = isSubtree(pRoot1,pRoot2);
}
if (!result){
result = HasSubtree(pRoot1.left,pRoot2);
}
if (!result){
result = HasSubtree(pRoot1.right,pRoot2);
}
}
return result;
}
function isSubtree(pRoot1,pRoot2) {
if (pRoot2 == null){
return true;
}
if (pRoot1 == null){
return false;
}
if (pRoot1.val!==pRoot2.val){
return false;
}
return isSubtree(pRoot1.left, pRoot2.left) && isSubtree(pRoot1.right,pRoot2.right);
}