-
Notifications
You must be signed in to change notification settings - Fork 0
/
pair sum using inorder BST.cpp
82 lines (77 loc) · 1.65 KB
/
pair sum using inorder BST.cpp
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
#include <stack>
int countNodes(BinaryTreeNode<int> *root) {
if(root == NULL) {
return 0;
}
return countNodes(root -> left) + countNodes(root -> right) + 1;
}
void printNodesSumToS(BinaryTreeNode<int> *root, int s) {
if(root == NULL) {
return;
}
int totalCount = countNodes(root);
int count = 0;
stack<BinaryTreeNode<int>*> inorder;
stack<BinaryTreeNode<int>*> revInorder;
BinaryTreeNode<int> *temp = root;
while(temp != NULL) {
inorder.push(temp);
temp = temp -> left;
}
temp = root;
while(temp != NULL) {
revInorder.push(temp);
temp = temp -> right;
}
while(count < totalCount - 1) {
BinaryTreeNode<int> *top1 = inorder.top();
BinaryTreeNode<int> *top2 = revInorder.top();
if(top1 -> data + top2 -> data == s) {
cout << top1 -> data << " " << top2 -> data << endl;
BinaryTreeNode<int> *top = top1;
inorder.pop();
count++;
if(top -> right != NULL) {
top = top -> right;
while(top != NULL) {
inorder.push(top);
top = top -> left;
}
}
top = top2;
revInorder.pop();
count++;
if(top -> left != NULL) {
top = top -> left;
while(top != NULL) {
revInorder.push(top);
top = top -> right;
}
}
}
else if(top1 -> data + top2 -> data > s) {
BinaryTreeNode<int> *top = top2;
revInorder.pop();
count++;
if(top -> left != NULL) {
top = top -> left;
while(top != NULL) {
revInorder.push(top);
top = top -> right;
}
}
}
else {
BinaryTreeNode<int> *top = top1;
inorder.pop();
count++;
if(top -> right != NULL) {
top = top -> right;
while(top != NULL) {
inorder.push(top);
top = top -> left;
}
}
}
}
}