oneby7

Binary Search Trees Using the ordering

393. Two Sum IV - Input is a BST

Easy

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

268101315192431

Input: root = [15, 6, 24, 2, 10, 19, 31, null, null, 8, 13] k = 27

Output: true

Explanation: 8 + 19 = 27. The 8 sits deep in the left subtree of the root, and the 19 in its right subtree.

Example 2

-8-349

Input: root = [4, -3, 9, -8], k = 8

Output: false

Explanation: 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

−10⁹010⁹

Input: root = [0, -1000000000, 1000000000], k = 0

Output: true

Explanation: 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.

root = [10, 5, 15, 3, 7, null, 18], k = 14

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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.