oneby7

Binary Search Trees Using the ordering

390. Insert into a Binary Search Tree

Medium

You are given root, the root node of a binary search tree, and an integer val that is not in the tree. Insert val into the tree and return the root of the result. The result must still be a binary search tree, and it must hold every value of the original tree plus val.

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.

Often more than one tree is a right answer, so the output does not show the shape. It lists the values of the tree you return in order: the left subtree first, then the node, then the right subtree, at every node. A tree lists its values from smallest to largest only when it is a binary search tree. So a right answer prints the old values and val, sorted.

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

112026293241506591

Input: root = [41, 20, 65, 11, 29, 50, 91, null, null, 26, 32] val = 30

Output: [11,20,26,29,30,32,41,50,65,91]

Explanation: 30 belongs between 29 and 32. One right answer puts a new node holding 30 as the left child of 32. Any other binary search tree with these ten values is accepted too.

Example 2

Input: root = [], val = 7

Output: [7]

Explanation: The tree is empty, so the new node holding 7 is the whole tree.

Example 3

−10⁹10⁹

Input: root = [-1000000000, null, 1000000000], val = 0

Output: [-1000000000,0,1000000000]

Explanation: 0 is larger than -109 and smaller than 109, so it can go in as the left child of 109.

Check your understanding

Work out the answer for this input before you write any code.

root = [40, 20, 60, 10, 30, 50, 70], val = 35

Constraints

  • 0 ≤ 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.
  • -109 ≤ val ≤ 109
  • val is not in the tree.

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.