-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path147. pair sum in BSt. cpp
48 lines (41 loc) · 1.07 KB
/
147. pair sum in 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
#include <bits/stdc++.h>
/**********************************************************
Following is the Binary Tree Node structure:
template <typename T>
class BinaryTreeNode {
public:
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this->data = data;
left = NULL;
right = NULL;
}
~BinaryTreeNode() {
if (left)
delete left;
if (right)
delete right;
}
};
***********************************************************/
void f(BinaryTreeNode<int>* root, vector<int> & inorder){
if(root==NULL)return;
f(root->left, inorder);
inorder.push_back(root->data);
f(root->right, inorder);
}
bool pairSumBst(BinaryTreeNode<int> *root, int k)
{
vector<int> inorder;
f(root, inorder);
int l = 0, h = inorder.size()-1;
while(l<h){
int sum = inorder[l] + inorder[h];
if(sum==k)return true;
if(sum<k)l++;
else h--;
}
return false;
}