Two Sum IV - Input Is A BST Problem
Description
LeetCode Problem 653.
Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input: root = [5,3,6,2,4,null,7], k = 9
Output: true
Example 2:
Input: root = [5,3,6,2,4,null,7], k = 28
Output: false
Example 3:
Input: root = [2,1,3], k = 4
Output: true
Example 4:
Input: root = [2,1,3], k = 1
Output: false
Example 5:
Input: root = [2,1,3], k = 3
Output: true
Constraints:
- The number of nodes in the tree is in the range [1, 10^4].
- -10^4<= Node.val <= 10^4
- root is guaranteed to be a valid binary search tree.
- -10^5<= k <= 10^5
Solution
Approach: In-Order Traversal and Two Pointers
An in-order traversal (left subtree, node, right subtree) of a binary search tree visits the values in increasing order. That turns the problem into Two Sum on a sorted array, which two pointers solve in a single pass.
- Traverse the tree in order and collect the values into
values. - Put
leftat the first index andrightat the last. - While
left < right, look attotal = values[left] + values[right]:total == k: found two nodes, returntrue.total < k: the sum must grow, andvalues[left]cannot reachkwith any partner (even the largest one remaining is too small), so moveleftright.total > k: by the same argument, moverightleft.
- If the pointers meet, no pair exists.
The loop condition is strict, left < right, because the two elements must be different nodes. With root = [1] and k = 2, the single node cannot be used twice, so the answer is false.
Complexity: O(n) time and O(n) space for the list of values and the recursion, where n is the number of nodes.
class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
values = [] # the BST's values in increasing order
def inorder(node: Optional[TreeNode]) -> None:
if node is None:
return
inorder(node.left)
values.append(node.val)
inorder(node.right)
inorder(root)
left, right = 0, len(values) - 1
while left < right: # two different nodes
total = values[left] + values[right]
if total == k:
return True
if total < k:
left += 1 # need a larger sum
else:
right -= 1 # need a smaller sum
return False
Now write it from memory
Close the write-up and solve it yourself against the tests.