AlgoInsight

DSA problem

Insert into a Binary Search Tree

MediumBST / Ordered SetPattern: BST / Ordered Settop600MicrosoftAmazonGoogleAppleBloomberg

You are given the root of a binary search tree and a value val to insert. Return the root of the BST after inserting a new node with value val. The input data is guaranteed such that the new value does not already exist in the original BST. Multiple valid insertions exist; any structurally valid BST is accepted.

A new value is always inserted at a leaf position. The BST ordering invariant tells you exactly where: starting from the root, descend left when val < node.val and right when val > node.val, repeating until you walk off the tree. That null spot is the only legal place for the new node.

A recursive formulation is concise — insert returns a tree whose subtree at the appropriate slot has been replaced — but it uses O(h) stack space. An iterative descent avoids that overhead by tracking a parent pointer alongside the walking pointer, then attaching the new node as either the parent's left or right child when the walk falls off.

The optimal solution walks a single pointer down the tree, remembering its parent. When the pointer becomes null, allocate a new node with value val, attach it under the parent on the appropriate side, and return the (unchanged) root. Special case: if the input root is null, return a fresh node as the new root. The algorithm runs in O(h) time and O(1) extra space.

Examples

Example 1
Input: root = [4,2,7,1,3], val = 5
Output: [4,2,7,1,3,5]
Explanation: Walk: 5 > 4 -> right to 7; 5 < 7 -> left to null. Insert 5 as the left child of 7.
Example 2
Input: root = [40,20,60,10,30,50,70], val = 25
Output: [40,20,60,10,30,50,70,null,null,25]
Explanation: Walk: 25 < 40 -> left to 20; 25 > 20 -> right to 30; 25 < 30 -> left to null. Insert 25 as the left child of 30.
Example 3
Input: root = [], val = 5
Output: [5]
Explanation: The tree is empty, so the new node becomes the root.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bsttreeiterativebinary-search-tree

Browse all DSA problems