-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubTreeOrNot.java
49 lines (38 loc) · 1.07 KB
/
SubTreeOrNot.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class SubTreeOrNot {
static class Node{
int data;
Node left ;
Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
public static boolean isSubTree(Node root, Node subtree){
if(root == null){
return false;
}
if(root.data == subtree.data){
if(isIdentical(root,subtree)){
return true;
}
}
return isSubTree(root.left,subtree) || isSubTree(root.right,subtree);
}
private static boolean isIdentical(Node root, Node subtree) {
if(root == null && subtree == null ){
return true;
}
else if( root == null || subtree == null || root.data != subtree.data ){
return false;
}
if(!isIdentical(root.left , subtree.left)){
return false;
}
if(!isIdentical(root.right, subtree.right)){
return false;
}
return true;
}
}