Insert into a Binary Search Tree


Link: LeetCode - Insert into a Binary Search Tree


Problem Statement

You are given the root of a binary search tree (BST) and an integer val.
Insert val into the BST such that its properties remain valid.
Return the root node of the BST after insertion.

Note: There may be multiple valid ways for the insertion, as long as the BST property is maintained.


Example

Input:

root = [4,2,7,1,3], val = 5

Output:

[4,2,7,1,3,5]

Constraints


Intuition

To insert a node in a Binary Search Tree, we:


Approach 1: Recursive

Java Code

class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        // Base case: place the node here
        if (root == null) {
            return new TreeNode(val);
        }

        // If value is less, insert into left subtree
        if (val < root.val) {
            root.left = insertIntoBST(root.left, val);
        } 
        // If value is greater, insert into right subtree
        else {
            root.right = insertIntoBST(root.right, val);
        }

        return root;
    }
}

Time and Space Complexity


Dry Run

Tree:

    4
   / \
  2   7
 / \
1   3

val = 5

Result:

    4
   / \
  2   7
 / \  /
1   3 5

Conclusion

Recursive insertion into a BST ensures we maintain all BST properties.
This problem is a great foundation for deeper BST operations like deletion and balancing.