Given two binary nonempty s and t, and the test is included in s t subtrees having the same structure and the node values. s of a subtree including all the descendants of a node and the node s. s can be seen as its own subtree.
Example 1:
given tree s:
3
/ \
4 5
/
1 2
Given a tree t:
4
/
1 2
Returns true, because t to s a subtree and nodes have the same configuration values.
Example 2:
given tree s:
3
/ \
4 5
/
1 2
/
0
Given a tree t:
4
/
1 2
Return false.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null){
return true;
}
if(p==null||q==null){
return false;
}
if(p.val!=q.val){
return false;
}
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
public boolean isSubtree(TreeNode s, TreeNode t) {
if(s==null){
return false;
}
if(t==null){
return true;
}
if(s.val==t.val&&isSameTree(s,t)){
return true;
}
return isSubtree(s.left,t)||isSubtree(s.right,t);
}
}