-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
57 lines (46 loc) · 1.32 KB
/
Copy pathsolution.java
File metadata and controls
57 lines (46 loc) · 1.32 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
/*
Definition for Node
class Node {
int data;
Node left;
Node right;
Node(int x) {
data = x;
left = right = null;
}
}
*/
class Solution {
// Function to check whether two trees are identical
boolean isSame(Node a, Node b) {
// If both nodes are null
// trees match till this point
if (a == null && b == null)
return true;
// If one node is null
// structures are different
if (a == null || b == null)
return false;
// Values must also match
if (a.data != b.data)
return false;
// Check left and right subtrees recursively
return isSame(a.left, b.left) &&
isSame(a.right, b.right);
}
public boolean isSubTree(Node root1, Node root2) {
// Empty tree is always a subtree
if (root2 == null)
return true;
// Main tree finished
// subtree not found
if (root1 == null)
return false;
// Check if trees are identical from current node
if (isSame(root1, root2))
return true;
// Otherwise continue searching
return isSubTree(root1.left, root2) ||
isSubTree(root1.right, root2);
}
}