Algo-Sim › Binary Trees & BST

Insert into a Binary Search Tree

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Search for the value until the walk falls off the tree, then attach the new node as a leaf there.

Problem

Insert val into a binary search tree and return the root. val is not in the tree yet. Any valid BST is accepted; the simple way adds it as a new leaf.

Constraints

Edge cases to test

Follow-up questions

How do you keep the tree balanced?
Self-balancing trees rotate after inserts: AVL keeps heights within 1, red–black within a factor of 2.
Recursive or iterative?
The iterative walk uses O(1) space and attaches the leaf to the last node visited.

Solution

Java

public TreeNode insertIntoBST(TreeNode root, int val) {
    TreeNode node = new TreeNode(val);
    if (root == null) return node;
    TreeNode curr = root;
    while (true) {
        if (val < curr.val) {
            if (curr.left == null) { curr.left = node; break; }
            curr = curr.left;
        } else {
            if (curr.right == null) { curr.right = node; break; }
            curr = curr.right;
        }
    }
    return root;
}

Python

def insert_into_bst(root, val):
    node = TreeNode(val)
    if not root:
        return node
    curr = root
    while True:
        if val < curr.val:
            if not curr.left:
                curr.left = node
                break
            curr = curr.left
        else:
            if not curr.right:
                curr.right = node
                break
            curr = curr.right
    return root

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    TreeNode *insertIntoBST(TreeNode *root, int val) {
        TreeNode *node = new TreeNode(val);
        if (root == nullptr)
            return node;
        TreeNode *curr = root;
        while (true) {
            if (val < curr->val) {
                if (curr->left == nullptr) {
                    curr->left = node;
                    break;
                }
                curr = curr->left;
            } else {
                if (curr->right == nullptr) {
                    curr->right = node;
                    break;
                }
                curr = curr->right;
            }
        }
        return root;
    }
};

More Binary Trees & BST problems