A binary search tree is handed to you through its root node, together with a number k. Return true if two different nodes in the tree have values that add up to exactly k, and false otherwise.
Example 1
Input: root = [8, 4, 12, 2, 6, 10, 14], k = 16 Output: true Why: 4 + 12 = 16
2 more examples and the constraints
Example 2
Input: root = [8, 4, 12, 2, 6, 10, 14], k = 30 Output: false Why: the two largest give only 12 + 14 = 26
Example 3
Input: root = [1], k = 2 Output: false Why: 1 + 1 would use the same node twice
Constraints
- 1 ≤ number of nodes ≤ 10,000
- −10,000 ≤ node value ≤ 10,000
- −100,000 ≤ k ≤ 100,000
- The tree is a valid binary search tree
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Search the tree for each partnerO(n·h)
- DFS with a set of seen valuesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 10,000-node chain | Verdict |
|---|---|---|---|
| Search for each partner | O(n·h) | Fine when balanced; slow on a chain | |
| DFS with a set | O(n) | Best; one visit per node |
n = number of nodes, h = height of the tree.
Edge cases to test
- One node. [1] with k = 2 is false: a node cannot pair with itself.
- Half of k is in the tree. [5, 2, 7] with k = 10: 5 + 5 is not allowed, and no other pair works.
- Negative values. [-2, -5, 0, -8] with k = −13 pairs −5 and −8.
- Skewed tree. A chain has height n; the set approach does not care.
Common mistakes
- Adding the value to the set before checking, so k = 2·val pairs a node with itself.
- Only comparing a node with its parent or children instead of with the whole tree.
- Reusing one Solution object (and its set) between calls without clearing it.
How to talk through it
- 1Clarify. Must the two nodes be different? Can values or k be negative? Is the tree balanced?
- 2Use the BST. For each node, binary search for k − val. Say it is O(n·h) and a chain makes h = n.
- 3Reduce to Two Sum. Any traversal plus a hash set of seen values finds the pair in one pass.
- 4Code the DFS. Check for the partner first, then add the value.
- 5Test out loud. Run the one-node case and k equal to twice a value.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?