Here is the interview question prompt, presented for reference.
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
100000
-100000
and 1000000
-100000
and 100000
O(n)
O(n)
You can see the full challenge with visuals at this link.
Challenges • Asked almost 7 years ago by Jake from AlgoDaily
This is the main discussion thread generated for Two Sum from BST.