标签:cti write 递归 treenode return off this roo title
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function HasSubtree(pRoot1, pRoot2)
{
// write code here
var result = false;
//定义result为false,如果pRoot1或pRoot2为空,直接返回result
//声明一个函数isSubtree,对pRoot1和pRoot2调用isSubtree,返回false后接着检测pRoot1的左子树和右子树
if(pRoot1 != null && pRoot2 != null){
result = isSubtree(pRoot1,pRoot2);
if(!result){
result = HasSubtree(pRoot1.left,pRoot2);
}
if(!result){
result = HasSubtree(pRoot1.right,pRoot2);
}
}
return result;
}
//当root1和root2的值不相等时直接返回false,再对root1和root2的左右子树分别递归调用isSubtree
//除了第一次,root和root2都不可能为空(在HasSubtree中有控制条件),后面如果root2为空的话说明root2是root1的子树,返回true,root1为空返回false
function isSubtree(root1,root2){
if(!root2){
return true;
}
if(!root1){
return false;
}
if(root1.val != root2.val){
return false;
}
return isSubtree(root1.left,root2.left) && isSubtree(root1.right,root2.right);
}
标签:cti write 递归 treenode return off this roo title
原文地址:https://www.cnblogs.com/3yleaves/p/9595257.html