Insert into a Binary Search Tree

You are given the `root` of a binary search tree (BST) and a value `val` to insert. Return the root of the BST after the insertion. It is guaranteed that `val` does not already exist in the tree. Several valid BSTs can hold the same values. This problem expects the standard insertion: walk down from the root, going left when `val` is smaller than the current node and right when it is larger, and attach the new node as a **leaf** at the first empty child you reach. No existing node moves.

30:00

Insert into a Binary Search Tree
medium
Free written solution
Topics
Companies

You are given the root of a binary search tree (BST) and a value val to insert. Return the root of the BST after the insertion. It is guaranteed that val does not already exist in the tree.

Several valid BSTs can hold the same values. This problem expects the standard insertion: walk down from the root, going left when val is smaller than the current node and right when it is larger, and attach the new node as a leaf at the first empty child you reach. No existing node moves.

Example 1:
Input: {"root":[4,2,7,1,3],"val":5}
Output: [4,2,7,1,3,5]
Constraints:
  • The number of nodes in the tree is in the range [0,104][0, 10^4].

  • −108≤Node.val≤108-10^8 \leq \text{Node.val} \leq 10^8

  • All the values Node.val are unique.

  • −108≤val≤108-10^8 \leq \text{val} \leq 10^8

  • It is guaranteed that val does not exist in the original BST.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[4,2,7,1,3],"val":5}

Create the new node 5. It will become a leaf; no existing node moves.

val = 5
path: -
nodes: 5
123475
new node
cur
path walked
empty child it will take
Variables
VariableValue
val5
curnull
depth0
DepthFunction Call
Stack empty
0/6