-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubTree.java
More file actions
85 lines (51 loc) · 1.54 KB
/
Copy pathSubTree.java
File metadata and controls
85 lines (51 loc) · 1.54 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package trees;
import strings.KMPSearch.*;
import static strings.KMPSearch.search;
public class SubTree {
public static Pairs helper(TreeNode T ,TreeNode S){
if(T==null && S==null){
return new Pairs(T,S,true);
}
if(T==null || S==null){
return new Pairs(T,S,false);
}
if(T.val==S.val){
Pairs left=helper(T.left,S.left);
Pairs right=helper(T.right,S.right);
if(left.isSub &&right.isSub){
return new Pairs(T,S,true);
}
}
Pairs ifleft=helper(T.left,S);
Pairs ifright=helper(T.right,S);
return new Pairs(T,S,ifleft.isSub||ifright.isSub);
}
public static boolean isSubtree(TreeNode T, TreeNode S) {
// Write your code here
return helper(T,S).isSub;
}
public static boolean anotherApproach(TreeNode T,TreeNode S){
if(T==S){
return true;
}
if(T==null){
return false;
}
if(!search(inorder(T),inorder(S)) || !search(postorder(T),postorder(S))){
return false;
}
return true;
}
public static String inorder(TreeNode root){
if(root==null){
return null;
}
return inorder(root.left)+" "+root.val+" "+inorder(root.right);
}
public static String postorder(TreeNode root){
if(root==null){
return null;
}
return postorder(root.left)+" "+postorder(root.right)+" "+root.val;
}
}