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.
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].
−104≤Node.val≤104
root is guaranteed to be a valid binary search tree.
−105≤k≤105
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.