Ctrl K

A New Leaf in a Search Tree

Medium
You are given the root of a binary search tree: in any node's left subtree all values are smaller than the node's, and in its right subtree all are larger. All values are distinct. Add the number value, which is not in the tree yet. Walk down from the root: if value is smaller than the current node's value, go left, otherwise go right. When the child you need is missing, hang a new node with value in its place. Don't move any other nodes. Return the root after the insertion (for an empty tree that is the new node).
Example 1
root=tree_node([10, 5, 15, None, 8]), value=7 → [10, 5, 15, None, 8, None, None, 7]

7 < 10, go left to 5; 7 > 5, go right to 8; 7 < 8 and 8 has no left child, so 7 goes there.

Example 2
root=tree_node([3, 1]), value=20 → [3, 1, 20]

20 is larger than the root, whose right slot is free.

Example 3
root=tree_node([]), value=-4 → [-4]

The tree is empty, so the new node becomes the root.

Constraints
  • 0 ≤ number of nodes ≤ 10⁴
  • -10⁸ ≤ Node.val, value ≤ 10⁸
  • All values in the tree are distinct and value is not among them
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCounting Search Tree Shapes MediumIs It a Search Tree? MediumTwo Mixed-Up Nodes MediumTree From a Sorted Chain MediumK-th Smallest in a Search Tree Medium
loading Python…
Input
root=tree_node([10, 5, 15, None, 8]), value=7
Expected
[10, 5, 15, None, 8, None, None, 7]

Run checks the first 3 tests in your browser. Submit checks all 65 tests on the server, hidden ones included.