Subtree of Another Tree 树的子结构
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.
考虑:首先寻找s树中与t树头结点值相同的节点,可以用递归实现。找到相同的节点后,比较该节点为头的节点和t树是否完全相同,这个过程也可以用递归完成。剑指Offer上此题与leetcode572题有一些不同之处:前者的子树为只要包含这个树就可以,而后者必须是t树与s树对应节点的所有后代都相同。所以前者递归结束的条件是只要t树的指针指向null即可,而后者必须两个指针全部指向null。
public boolean isSubtree(TreeNode s, TreeNode t) {
if(s!=null && t!=null){
if(s.val == t.val){
if(helper(s,t))
return true;
}
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
return false;
}
boolean helper(TreeNode s, TreeNode t) {
if(t == null)
return true;
if(s == null)
return false;
if(t.val != s.val)
return false;
return helper(s.left, t.left) && helper(s.right, t.right);
}
public boolean isSubtree(TreeNode s, TreeNode t) {
if(s!=null && t!=null){
if(s.val == t.val){
if(helper(s,t))
return true;
}
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
return false;
}
boolean helper(TreeNode s, TreeNode t) {
if(t == null && s == null)
return true;
if(s == null || t == null)
return false;
if(t.val != s.val)
return false;
return helper(s.left, t.left) && helper(s.right, t.right);
}