Binary Search Trees Using the ordering
393. Two Sum IV - Input is a BST
You are given root, the root node of a binary search tree, and an integer k. Return true if two
different nodes of the tree hold values that add up to k, and false otherwise. One node cannot be used
twice.
In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. The values in the tree are distinct.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [15, 6, 24, 2, 10, 19, 31, null, null, 8, 13]
k = 27
trueExplanation: 8 + 19 = 27. The 8 sits deep in the left subtree of the root, and the 19 in its right subtree.
Example 2
Input: root = [4, -3, 9, -8], k = 8
falseExplanation: 4 + 4 = 8, but only one node holds 4, and one node cannot be used twice. No other pair adds up to 8.
Example 3
Input: root = [0, -1000000000, 1000000000], k = 0
trueExplanation: The smallest and the largest values, −109 and 109, add up to 0.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
- The tree is a binary search tree, and its values are distinct.
-2·109 ≤ k ≤ 2·109
Clarifying questions
What you would ask an interviewer before writing any code.