-
Notifications
You must be signed in to change notification settings - Fork 116
/
BST and Binary Tree Assignment::Pair sum in a BST
88 lines (71 loc) · 2.19 KB
/
BST and Binary Tree Assignment::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
81
82
83
84
85
86
87
88
import java.util.ArrayList;
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 printNodesSumToS(BinaryTreeNode<Integer> root, int s) {
// printNodesSumToS(root ,root ,s);
// }
// public static void printNodesSumToS(BinaryTreeNode<Integer> temp1 ,BinaryTreeNode<Integer> temp2 ,int s){
// if(temp1 == null){
// return;
// }
// if(temp2 == null){
// return;
// }
// printNodesSumToS(temp1.left, temp2 ,s);
// printNodesSumToS(temp1, temp2.right ,s);
// int sum = temp1.data + temp2.data;
// if(sum == s){
// System.out.println(temp1.data+" "+temp2.data);
// printNodesSumToS(temp1.right ,temp2.left ,s);
// //printNodesSumToS(temp2.left);
// }else if(sum > s){
// printNodesSumToS(temp1 ,temp2.left ,s);
// }else{
// printNodesSumToS(temp1.right ,temp2 ,s);
// }
// }
public static void printNodesSumToS(BinaryTreeNode<Integer> root, int sum) {
Queue<BinaryTreeNode<Integer>> pendingNodes = new Queue<>();
ArrayList<Integer> list = new ArrayList<>();
pendingNodes.enqueue(root);
while (!pendingNodes.isEmpty()) {
BinaryTreeNode<Integer> frontNode = null;
int counter = pendingNodes.size();
for (int i = 0; i < counter; i++) {
try {
frontNode = pendingNodes.dequeue();
} catch (QueueEmptyException e) {
e.printStackTrace();
}
list.add(frontNode.data);
if (frontNode.left != null) {
pendingNodes.enqueue(frontNode.left);
}
if (frontNode.right != null) {
pendingNodes.enqueue(frontNode.right);
}
}
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j != i && j < list.size(); j++) {
if (list.get(i) + list.get(j) == sum) {
if (list.get(i) < list.get(j)) {
System.out.println(list.get(i) + " " + list.get(j));
} else {
System.out.println(list.get(j) + " " + list.get(i));
}
}
}
}
}
}