-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find Common Nodes in two BSTs
66 lines (36 loc) · 1.2 KB
/
Find Common Nodes in two BSTs
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
//User function Template for Java
class Solution
{
//Function to find the nodes that are common in both BST.
public static ArrayList<Integer> findCommon(Node root1,Node root2)
{
//code here
HashMap<Integer, Integer> hm = new HashMap<>();
inOrder1(root1, hm);
ArrayList<Integer> result = new ArrayList<>();
inOrder2(root2, hm, result);
return result;
}
public static void inOrder1(Node root, HashMap<Integer, Integer> map)
{
if(root == null)
{
return;
}
inOrder1(root.left, map);
map.put(root.data, 1);
inOrder1(root.right, map);
}
public static void inOrder2(Node root, HashMap<Integer, Integer> map, ArrayList<Integer> result)
{
if(root == null)
{
return;
}
inOrder2(root.left, map, result);
if(map.containsKey(root.data)){
result.add(root.data);
}
inOrder2(root.right, map, result);
}
}