KatInterview

784. Insert into a Binary Search Tree

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Traverse and Insert

This problem asks us to insert a new value into a Binary Search Tree (BST) while maintaining its properties. The key property of a BST is that for any given node, all values in its left subtree are smaller, and all values in its right subtree are larger. Since the problem guarantees the new value doesn't already exist, we just need to find the correct leaf position to attach the new node.

Solution

Insert into a Binary Search Tree in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        # Base case: If the current node is null, we've found the insertion point.
        # Create a new node with the given value and return it.
        if not root:
            return TreeNode(val)

        # If the value to insert is less than the current node's value,
        # it belongs in the left subtree.
        if val < root.val:
            # Recursively call insert on the left subtree.
            # The returned node (either the existing left child or the new node)
            # is assigned as the new left child of the current root.
            root.left = self.insertIntoBST(root.left, val)
        else: # val > root.val (guaranteed no duplicates)
            # If the value is greater, it belongs in the right subtree.
            # Recursively call insert on the right subtree.
            root.right = self.insertIntoBST(root.right, val)

        # Return the (possibly modified) root of the current subtree.
        return root

Insert into a Binary Search Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        // Base case: If the current node is null, we've found the insertion point.
        // Create a new node with the given value and return it.
        if (root == null) {
            return new TreeNode(val);
        }

        // If the value to insert is less than the current node's value,
        // it belongs in the left subtree.
        if (val < root.val) {
            // Recursively call insert on the left subtree.
            // The returned node (either the existing left child or the new node)
            // is assigned as the new left child of the current root.
            root.left = insertIntoBST(root.left, val);
        } else { // val > root.val (guaranteed no duplicates)
            // If the value is greater, it belongs in the right subtree.
            // Recursively call insert on the right subtree.
            root.right = insertIntoBST(root.right, val);
        }

        // Return the (possibly modified) root of the current subtree.
        return root;
    }
}

Insert into a Binary Search Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        // Base case: If the current node is null, we've found the insertion point.
        // Create a new node with the given value and return it.
        if (root == nullptr) {
            return new TreeNode(val);
        }

        // If the value to insert is less than the current node's value,
        // it belongs in the left subtree.
        if (val < root->val) {
            // Recursively call insert on the left subtree.
            // The returned node (either the existing left child or the new node)
            // is assigned as the new left child of the current root.
            root->left = insertIntoBST(root->left, val);
        } else { // val > root->val (guaranteed no duplicates)
            // If the value is greater, it belongs in the right subtree.
            // Recursively call insert on the right subtree.
            root->right = insertIntoBST(root->right, val);
        }

        // Return the (possibly modified) root of the current subtree.
        return root;
    }
};

Insert into a Binary Search Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
    // Base case: If the current node is null, we've found the insertion point.
    // Create a new node with the given value and return it.
    if (root === null) {
        return new TreeNode(val);
    }

    // If the value to insert is less than the current node's value,
    // it belongs in the left subtree.
    if (val < root.val) {
        // Recursively call insert on the left subtree.
        // The returned node (either the existing left child or the new node)
        // is assigned as the new left child of the current root.
        root.left = insertIntoBST(root.left, val);
    } else { // val > root.val (guaranteed no duplicates)
        // If the value is greater, it belongs in the right subtree.
        // Recursively call insert on the right subtree.
        root.right = insertIntoBST(root.right, val);
    }

    // Return the (possibly modified) root of the current subtree.
    return root;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.