问题描述:
判断以subRoot为根节点的树是否为以root为根节点的树的子树
subRoot树为root树的子树必须满足三个条件之一:(1)subRoot树是root树左子树的子树 (2)subRoot树是root树右子树的子树 (3)subRoot树与root树相同
判断两棵树是否相同的方法在之前的题目中遇到过
代码如下:
class Solution {
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if(root==null) return false;
return (isSame(root, subRoot)||isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot));
}
//this function checks whether two trees rooted at
//a and b are same or not
private boolean isSame(TreeNode a, TreeNode b){
if((a==null)&&(b==null)) return true; //if both a and b are null -> same tree
else if((a==null)&&(b!=null)) return false; //if one node is null -> not same
else if((a!=null)&&(b==null)) return false;
else{ //if all node not-null -> check value of root and their subtrees
return ((a.val==b.val) && isSame(a.left, b.left) && isSame(a.right, b.right));
}
}
}
时间复杂度: O(logn), n 是root树的节点数量