-
Notifications
You must be signed in to change notification settings - Fork 1
/
brothers-from-different-root.java
62 lines (55 loc) · 1.66 KB
/
brothers-from-different-root.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Solution
{
// Helper function to perform inorder traversal of BST and store values in a list
private static void inorderTraversal(Node root, List<Integer> list)
{
if (root != null)
{
inorderTraversal(root.left, list);
list.add(root.data);
inorderTraversal(root.right, list);
}
}
// Helper function to perform reverse inorder traversal of BST and store values in a list
private static void reverseInorderTraversal(Node root, List<Integer> list)
{
if (root != null)
{
reverseInorderTraversal(root.right, list);
list.add(root.data);
reverseInorderTraversal(root.left, list);
}
}
public static int countPairs(Node root1, Node root2, int x)
{
// Lists to store inorder and reverse inorder traversals of the BSTs
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
// Perform inorder and reverse inorder traversals
inorderTraversal(root1, list1);
reverseInorderTraversal(root2, list2);
// Pointers for traversal
int i = 0, j = 0;
int count = 0;
// Two-pointer approach to find pairs with sum equal to x
while (i < list1.size() && j < list2.size())
{
int sum = list1.get(i) + list2.get(j);
if (sum == x)
{
count++;
i++;
j++;
}
else if (sum < x)
{
i++;
}
else
{
j++;
}
}
return count;
}
}