forked from Jensenczx/CodeEveryday
-
Notifications
You must be signed in to change notification settings - Fork 0
/
41_isSubtree.java
30 lines (29 loc) · 924 Bytes
/
41_isSubtree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
/**
* @param T1, T2: The roots of binary tree.
* @return: True if T2 is a subtree of T1, or false.
*/
public boolean isSubtree(TreeNode T1, TreeNode T2) {
if(T2==null)
return true;
boolean flag = false;
if(T1!=null&&T2!=null){
if(T1.val==T2.val){
flag = isSubtree1(T1.left,T2.left)&&isSubtree1(T1.right,T2.right);
}
if(!flag)
flag = isSubtree(T1.left,T2)||isSubtree(T1.right,T2);
}
return flag;
}
public boolean isSubtree1(TreeNode T1, TreeNode T2) {
// write your code here
if(T2==null&&T1==null)
return true;
else if(T2==null||T1==null)
return false;
if(T2.val==T1.val)
return isSubtree1(T1.left,T2.left)&&isSubtree1(T1.right,T2.right);
return false;
}
}