Two Sum from BST
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Description
This problem is a fun combination of the famous Two Sum problem combined with a binary search tree. Given the root of a binary search tree, and a target integer K, return true if there exist two nodes in the said tree whose sum equals K. If no pair fits this match, return false.
Say we are given this tree:
/***
Input:
5
/ \
3 8
/
1
***/
Each node is defined in the following manner:
class Node {
constructor(val) {
this.value = val;
this.left = null;
this.right = null;
}
}
And thus the below setup and execution code should hold true:
const root = new Node(5);
root.left = new Node(3);
root.right = new Node(8);
root.left.left = new Node(1);
const target = 11;
twoSumFromBST(root, target);
// true because 3 + 8 = 11

Constraints
- Number of vertices in the tree <=
100000 - The values in the vertices will be between
-100000and1000000 - The target value will be between
-100000and100000 - Expected time complexity :
O(n) - Expected space complexity :
O(n)
```js
function inOrder(root) {}
function twoSumFromBST(root, target) {
// Fill in this method
return root;
}
class Node {
constructor(val) {
this.value = val;
this.left = null;
this.right = null;
}
}
const root = new Node(5);
root.left = new Node(3);
root.right = new Node(8);
root.left.left = new Node(1);
const target = 11;
console.log(twoSumFromBST(root, target));
// true because 3 + 8 = 11
```
CONTINUE WITH ALGODAILY PREMIUM
Keep going with the complete tutorial.
Unlock the remaining explanations and exercises, alongside the full learning library.
Explore Premium →