122. Two sum in BST

Given the root of a binary search tree and an integer k.Return true if there exist two elements in the BST such that their sum is equal to k otherwise false.

Example 1:

Input : root = [5, 3, 6, 2, 4, null, 7] , k = 9

Output : true

Explanation :

The BST contains multiple pair of nodes that sum up to k.

3 + 6 => 9.

5 + 4 => 9.

2 + 7 => 9.

Example 2:

Input : root = [5, 3, 6, 2, 4, null, 7] , k = 14

Output : false

Explanation :

There is no pair in given BST that sum up to k.

Now Your Turn!

Pick the correct output for the given input

Input : root = [5, 3, 6, 2, 4, null, 7] , k = 12

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 104
  • -104 <= Node.val <= 104
  • -105 <= k <= 105

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution{
public:
bool twoSumBST(TreeNode* root, int k){
//your code goes here
}
};
Test Case

Input:

K
Root