-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPair_Sum_in_BST.txt
96 lines (80 loc) · 2.94 KB
/
Pair_Sum_in_BST.txt
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
Pair sum in a BST
Send Feedback
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
import java.util.*;
public class Solution {
/* Binary Tree Node class
*
* class BinaryTreeNode<T> {
T data;
BinaryTreeNode<T> left;
BinaryTreeNode<T> right;
public BinaryTreeNode(T data) {
this.data = data;
}
}
*/
public static void pairSum(ArrayList<Integer> arr, int num)
{
int i = 0, j = arr.size() - 1;
int count = 0;
while (i != j && j > i && i < arr.size() - 1 && j > 0) {
if ((arr.get(i) + arr.get(j)) > num ) {
j --;
}
else if ((arr.get(j) + arr.get(i)) < num) {
i ++;
}
else {
System.out.println(arr.get(i) + " " + arr.get(j));
if(arr.get(j - 1) == arr.get(j) && i != j - 1){
j --;
count ++;
}
else {
if(arr.get(i) == arr.get(i + 1)) {
j = j + count;
count = 0;
}
else
j --;
i ++;
}
}
}
}
public static ArrayList<Integer> convertArray(BinaryTreeNode<Integer> root) {
if(root == null) {
ArrayList<Integer> arr = new ArrayList<Integer>();
return arr;
}
ArrayList<Integer> ans = new ArrayList<Integer>();
ArrayList<Integer> smallAnsLeft = convertArray(root.left);
ans.addAll(smallAnsLeft);
ans.add(root.data);
ArrayList<Integer> smallAnsRight = convertArray(root.right);
ans.addAll(smallAnsRight);
return ans;
}
public static void printNodesSumToS(BinaryTreeNode<Integer> root, int s) {
// Write your code here
ArrayList<Integer> arr = convertArray(root);
pairSum(arr, s);
}
}