Two Sum IV - Input is a BST

Given the root of a binary search tree and an integer k, return true if there are two different nodes in the tree whose values add up to k, and false otherwise.

30:00

Two Sum IV - Input is a BST
easy
Free written solution
Topics
Companies

Given the root of a binary search tree and an integer k, return true if there are two different nodes in the tree whose values add up to k, and false otherwise.

Example 1:
Input: {"root":[5,3,6,2,4,null,7],"k":9}
Output: true
Constraints:
  • The number of nodes in the tree is in the range [1,104][1, 10^4].

  • −104≤Node.val≤104-10^4 \leq \text{Node.val} \leq 10^4

  • root is guaranteed to be a valid binary search tree.

  • −105≤k≤105-10^5 \leq k \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

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

Find two different nodes that add up to k = 9. First flatten the BST into sorted order with an inorder walk.

536247vals (inorder)
target k = 9, collecting values in sorted order
on inorder stack
just collected
lo
hi
pair found
Each node sits directly above its slot in the sorted array.
Variables
VariableValue
k9
vals[]
lo-
hi-
s-
DepthFunction Call
Stack empty
0/15