-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST2-Pair sum in a BST
80 lines (69 loc) · 2.09 KB
/
BST2-Pair sum in a BST
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
Given a binary search tree and an integer S, find pair of nodes in the BST which sum to S. You can use extra space of the order of O(log n).
Note:
1. Assume BST contains all unique elements.
2. In a pair, print the smaller element first.
Input Format :
The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node.
The following line of input contains an integer, that denotes the value of S.
Output format:
You have to print each pair in a different line (pair elements separated by space). The order of different pairs, to be printed, does not matter.
Constraints:
Time Limit: 1 second
Sample Input 1:
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
12
Sample Output 1:
2 10
5 7
*********************************Solution*********************************
import java.util.*;
public static void printNodesSumToS(BinaryTreeNode<Integer> root, int s) {
if (root == null)
return;
else
{
ArrayList<Integer> arr = convertToArray(root);
Collections.sort(arr);
printPairSum(arr, s);
}
}
private static ArrayList<Integer> convertToArray(BinaryTreeNode<Integer> root) {
if (root == null)
{
ArrayList<Integer> arr = new ArrayList<Integer>();
return arr;
}
ArrayList<Integer> currArr = new ArrayList<Integer>();
ArrayList<Integer> leftArr = convertToArray(root.left);
if (!leftArr.isEmpty())
{
currArr.addAll(leftArr);
}
currArr.add(root.data);
ArrayList<Integer> rightArr = convertToArray(root.right);
if (!rightArr.isEmpty())
{
currArr.addAll(rightArr);
}
return currArr;
}
private static void printPairSum(ArrayList<Integer> arr, int s) {
int i = 0, j = arr.size() - 1;
while (i < j)
{
int a = arr.get(i);
int b = arr.get(j);
if (a + b > s)
{
j--;
} else if (a + b < s)
{
i++;
} else
{
System.out.println(a + " " + b);
i++;
j--;
}
}
}