树的子结构
输入两棵二叉树A,B,判断B是不是A的子结构。
我们规定空树不是任何树的子结构。
样例
树A:
8
/ \
8 7
/ \
9 2
/ \
4 7
树B:
8
/ \
9 2
返回 true ,因为B是A的子结构。
递归
时间复杂度 O(nm)
n 是树A中的节点数,m是树B中的节点数
class Solution {
public boolean hasSubtree(TreeNode root1, TreeNode root2) {
boolean res = false;
if(root1 != null && root2 != null){
if(root1.val == root2.val){
res = helpHasSubtree(root1,root2);
}
if(!res){
res = hasSubtree(root1.left,root2);
}
if(!res){
res = hasSubtree(root1.right,root2);
}
}
return res;
}
public boolean helpHasSubtree(TreeNode root1, TreeNode root2){
if(root2 == null){
return true;
}
if(root1 == null){
return false;
}
if(root1.val != root2.val){
return false;
}
return helpHasSubtree(root1.left,root2.left) && helpHasSubtree(root1.right,root2.right);
}
}
进阶版
时间复杂度 O(nm)
n 是树A中的节点数,m是树B中的节点数
class Solution {
boolean hasSubtree(TreeNode pRoot1, TreeNode pRoot2) {
if(pRoot1 == null || pRoot2 == null){
return false;
}
if(isPart(pRoot1, pRoot2)){
return true;
}
return hasSubtree(pRoot1.left,pRoot2) || hasSubtree(pRoot1.right,pRoot2);
}
boolean isPart(TreeNode root1, TreeNode root2) {
if(root2 == null){
return true;
}
if(root1 == null || root1.val != root2.val){
return false;
}
return isPart(root1.left,root2.left) && isPart(root1.right,root2.right);
}
}