AcWing 37. 树的子结构
原题链接
简单
作者:
Zh1995
,
2019-08-11 19:39:30
,
所有人可见
,
阅读 865
class Solution {
public boolean isSame(TreeNode r1,TreeNode r2)
{
if(r2==null)//r2为空,不论r1是否为空
return true;
else if(r1==null)
return false;
else if(r1.val!=r2.val)//二者均不为空且值不想等
return false;
else
return isSame(r1.left,r2.left) && isSame(r1.right,r2.right);
}
//依次遍历整棵树
public boolean hasSubtree(TreeNode pRoot1, TreeNode pRoot2) {
if(pRoot1==null||pRoot2==null)
return false;
if(isSame(pRoot1,pRoot2))
return true;
return hasSubtree(pRoot1.right,pRoot2)||hasSubtree(pRoot1.left,pRoot2);
}
}