Insertion in Binary Search Tree (BST)

Last Updated : 29 Jul, 2026

Given the root of a Binary Search Tree (BST) and an integer key, insert a new node with value key into the BST. Return the root of the modified tree after the insertion.

Note: All the nodes have distinct values in the BST and the new value to be inserted is not present in the BST.

Example:

Input: root = [2, 1, 3], key = 4

blobid0_1749203692

Output: [2, 1, 3, N, N, N, 4]
Explanation: After inserting the node 4, the new tree will be [2, 1, 3, N, N, N, 4].

blobid0_1785319358

Input: root = [2, 1, 3, N, N, N, 6], key = 4

blobid1_1749203742

Output: [2, 1, 3, N, N, N, 4, N, 6]
Explanation: After inserting the node 4, the new tree will be [2, 1, 3, N, N, N, 4, N, 6].

2056958493
Try It Yourself
redirect icon

[Naive Approach] Recursive Insertion - O(h) Time and O(h) Space

The idea is to insert the new key at a position that preserves the Binary Search Tree (BST) property. Starting from the root, compare the key with the current node. If the key is smaller, move to the left child; otherwise, move to the right child. Continue this process until a NULL child is reached, then insert the new node at that position as a leaf node. This ensures that the BST property remains valid after the insertion.

C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

// Structure for a Binary Search Tree node
class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Insert a node into the BST
Node* insert(Node* root, int key) {

    // If tree is empty, create a new node
    if (root == nullptr) {
        return new Node(key);
    }

    // Insert into the left subtree
    if (key < root->data) {
        root->left = insert(root->left, key);
    }

    // Insert into the right subtree
    else {
        root->right = insert(root->right, key);
    }

    return root;
}

// Print the tree in level order
void printTree(Node* root) {
    if (root == nullptr) {
        cout << "[]";
        return;
    }

    vector<string> ans;
    queue<Node*> q;
    q.push(root);

    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();

        if (curr == nullptr) {
            ans.push_back("N");
        } else {
            ans.push_back(to_string(curr->data));
            q.push(curr->left);
            q.push(curr->right);
        }
    }

    // Remove trailing N's
    while (!ans.empty() && ans.back() == "N") {
        ans.pop_back();
    }

    cout << "[";
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i];
        if (i + 1 < ans.size()) {
            cout << ", ";
        }
    }
    cout << "]";
}

int main() {

    // Create the BST
    //        22
    //       /  \
    //     12    30
    //    /  \
    //   8    20
    //          \
    //           21

    Node* root = new Node(22);
    root->left = new Node(12);
    root->right = new Node(30);
    root->left->left = new Node(8);
    root->left->right = new Node(20);
    root->left->right->right = new Node(21);

    int key = 15;

    root = insert(root, key);

    printTree(root);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Structure for a Binary Search Tree node
struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

struct Node* createNode(int x) {
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp->data = x;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

// Insert a node into the BST
struct Node* insert(struct Node* root, int key) {

    // If tree is empty, create a new node
    if (root == NULL) {
        return createNode(key);
    }

    // Insert into the left subtree
    if (key < root->data) {
        root->left = insert(root->left, key);
    }

    // Insert into the right subtree
    else {
        root->right = insert(root->right, key);
    }

    return root;
}

// Print the tree in level order
void printTree(struct Node* root) {
    if (root == NULL) {
        printf("[]");
        return;
    }

    struct Node* queue[100];
    char ans[100][10];
    int front = 0, rear = 0, size = 0;

    queue[rear++] = root;

    while (front < rear) {
        struct Node* curr = queue[front++];

        if (curr == NULL) {
            sprintf(ans[size++], "N");
        } else {
            sprintf(ans[size++], "%d", curr->data);
            queue[rear++] = curr->left;
            queue[rear++] = curr->right;
        }
    }

    // Remove trailing N's
    while (size > 0 && strcmp(ans[size - 1], "N") == 0) {
        size--;
    }

    printf("[");
    for (int i = 0; i < size; i++) {
        printf("%s", ans[i]);
        if (i + 1 < size) {
            printf(", ");
        }
    }
    printf("]");
}

int main() {

    // Create the BST
    //        22
    //       /  \
    //     12    30
    //    /  \
    //   8    20
    //          \
    //           21

    struct Node* root = createNode(22);
    root->left = createNode(12);
    root->right = createNode(30);
    root->left->left = createNode(8);
    root->left->right = createNode(20);
    root->left->right->right = createNode(21);

    int key = 15;

    root = insert(root, key);

    printTree(root);

    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.List;
import java.util.ArrayList;

// Structure for a Binary Search Tree node
class Node {
    int data;
    Node left;
    Node right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

public class GFG {

    // Insert a node into the BST
    static Node insert(Node root, int key) {

        // If tree is empty, create a new node
        if (root == null) {
            return new Node(key);
        }

        // Insert into the left subtree
        if (key < root.data) {
            root.left = insert(root.left, key);
        }

        // Insert into the right subtree
        else {
            root.right = insert(root.right, key);
        }

        return root;
    }

    // Print the tree in level order
    static void printTree(Node root) {
        if (root == null) {
            System.out.print("[]");
            return;
        }

        ArrayList<String> ans = new ArrayList<>();
        Queue<Node> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {
            Node curr = q.poll();

            if (curr == null) {
                ans.add("N");
            } else {
                ans.add(String.valueOf(curr.data));
                q.offer(curr.left);
                q.offer(curr.right);
            }
        }

        // Remove trailing N's
        while (!ans.isEmpty() && ans.get(ans.size() - 1).equals("N")) {
            ans.remove(ans.size() - 1);
        }

        System.out.print("[");
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i));
            if (i + 1 < ans.size()) {
                System.out.print(", ");
            }
        }
        System.out.print("]");
    }

    public static void main(String[] args) {

        // Create the BST
        //        22
        //       /  \
        //     12    30
        //    /  \
        //   8    20
        //          \
        //           21

        Node root = new Node(22);
        root.left = new Node(12);
        root.right = new Node(30);
        root.left.left = new Node(8);
        root.left.right = new Node(20);
        root.left.right.right = new Node(21);

        int key = 15;

        root = insert(root, key);

        printTree(root);
    }
}
Python
from collections import deque

# Structure for a Binary Search Tree node
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Insert a node into the BST
def insert(root, key):

    # If tree is empty, create a new node
    if root is None:
        return Node(key)

    # Insert into the left subtree
    if key < root.data:
        root.left = insert(root.left, key)

    # Insert into the right subtree
    else:
        root.right = insert(root.right, key)

    return root

# Print the tree in level order
def printTree(root):
    if root is None:
        print("[]")
        return

    ans = []
    q = deque([root])

    while q:
        curr = q.popleft()

        if curr is None:
            ans.append("N")
        else:
            ans.append(str(curr.data))
            q.append(curr.left)
            q.append(curr.right)

    # Remove trailing N's
    while ans and ans[-1] == "N":
        ans.pop()

    print("[" + ", ".join(ans) + "]")

if __name__ == "__main__":

    # Create the BST
    #        22
    #       /  \
    #     12    30
    #    /  \
    #   8    20
    #          \
    #           21

    root = Node(22)
    root.left = Node(12)
    root.right = Node(30)
    root.left.left = Node(8)
    root.left.right = Node(20)
    root.left.right.right = Node(21)

    key = 15

    root = insert(root, key)

    printTree(root)
C#
using System;
using System.Collections.Generic;

// Structure for a Binary Search Tree node
class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GFG {

    // Insert a node into the BST
    static Node insert(Node root, int key) {

        // If tree is empty, create a new node
        if (root == null) {
            return new Node(key);
        }

        // Insert into the left subtree
        if (key < root.data) {
            root.left = insert(root.left, key);
        }

        // Insert into the right subtree
        else {
            root.right = insert(root.right, key);
        }

        return root;
    }

    // Print the tree in level order
    static void printTree(Node root) {
        if (root == null) {
            Console.Write("[]");
            return;
        }

        List<string> ans = new List<string>();
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {
            Node curr = q.Dequeue();

            if (curr == null) {
                ans.Add("N");
            } else {
                ans.Add(curr.data.ToString());
                q.Enqueue(curr.left);
                q.Enqueue(curr.right);
            }
        }

        // Remove trailing N's
        while (ans.Count > 0 && ans[ans.Count - 1] == "N") {
            ans.RemoveAt(ans.Count - 1);
        }

        Console.Write("[");
        for (int i = 0; i < ans.Count; i++) {
            Console.Write(ans[i]);
            if (i + 1 < ans.Count) {
                Console.Write(", ");
            }
        }
        Console.Write("]");
    }

    static void Main() {

        // Create the BST
        //        22
        //       /  \
        //     12    30
        //    /  \
        //   8    20
        //          \
        //           21

        Node root = new Node(22);
        root.left = new Node(12);
        root.right = new Node(30);
        root.left.left = new Node(8);
        root.left.right = new Node(20);
        root.left.right.right = new Node(21);

        int key = 15;

        root = insert(root, key);

        printTree(root);
    }
}
Javascript
// Structure for a Binary Search Tree node
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Insert a node into the BST
function insert(root, key) {

    // If tree is empty, create a new node
    if (root === null) {
        return new Node(key);
    }

    // Insert into the left subtree
    if (key < root.data) {
        root.left = insert(root.left, key);
    }

    // Insert into the right subtree
    else {
        root.right = insert(root.right, key);
    }

    return root;
}

// Print the tree in level order
function printTree(root) {
    if (root === null) {
        process.stdout.write("[]");
        return;
    }

    const ans = [];
    const q = [root];

    while (q.length > 0) {
        const curr = q.shift();

        if (curr === null) {
            ans.push("N");
        } else {
            ans.push(curr.data.toString());
            q.push(curr.left);
            q.push(curr.right);
        }
    }

    // Remove trailing N's
    while (ans.length > 0 && ans[ans.length - 1] === "N") {
        ans.pop();
    }

    process.stdout.write("[" + ans.join(", ") + "]");
}

// Driver code

// Create the BST
//        22
//       /  \
//     12    30
//    /  \
//   8    20
//          \
//           21

let root = new Node(22);
root.left = new Node(12);
root.right = new Node(30);
root.left.left = new Node(8);
root.left.right = new Node(20);
root.left.right.right = new Node(21);

let key = 15;

root = insert(root, key);

printTree(root);

Output
[22, 12, 30, 8, 20, N, N, N, N, 15, 21]

[Expected Approach] Iterative Traversal - O(h) Time and O(1) Space

The idea is to iteratively traverse the BST to find the correct position for the new key. Starting from the root, move left if the key is smaller; otherwise, move right. When a NULL child is found, insert the new node there as a leaf node, preserving the BST property.

C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

// Structure for a Binary Search Tree node
class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Insert a node into the BST
Node* insert(Node* root, int key) {
    Node* temp = new Node(key);

    // If tree is empty
    if (root == nullptr) {
        return temp;
    }

    // Find the node who is going to
    // have the new node as its child
    Node* curr = root;
    while (curr != nullptr) {
        if (curr->data > key && curr->left != nullptr) {
            curr = curr->left;
        } else if (curr->data < key && curr->right != nullptr) {
            curr = curr->right;
        } else {
            break;
        }
    }

    // If key is smaller, make it left
    // child, else right child
    if (curr->data > key) {
        curr->left = temp;
    } else {
        curr->right = temp;
    }

    return root;
}

// Print the tree in level order
void printTree(Node* root) {
    if (root == nullptr) {
        cout << "[]";
        return;
    }

    vector<string> ans;
    queue<Node*> q;
    q.push(root);

    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();

        if (curr == nullptr) {
            ans.push_back("N");
        } else {
            ans.push_back(to_string(curr->data));
            q.push(curr->left);
            q.push(curr->right);
        }
    }

    // Remove trailing N's
    while (!ans.empty() && ans.back() == "N") {
        ans.pop_back();
    }

    cout << "[";
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i];
        if (i + 1 < ans.size()) {
            cout << ", ";
        }
    }
    cout << "]";
}

int main() {

    // Create the BST
    //        22
    //       /  \
    //     12    30
    //    /  \
    //   8    20
    //          \
    //           21

    Node* root = new Node(22);
    root->left = new Node(12);
    root->right = new Node(30);
    root->left->left = new Node(8);
    root->left->right = new Node(20);
    root->left->right->right = new Node(21);

    int key = 15;

    root = insert(root, key);

    printTree(root);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Structure for a Binary Search Tree node
struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

struct Node* createNode(int x) {
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp->data = x;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

// Insert a node into the BST
struct Node* insert(struct Node* root, int key) {
    struct Node* temp = createNode(key);

    // If tree is empty
    if (root == NULL) {
        return temp;
    }

    // Find the node who is going to
    // have the new node as its child
    struct Node* curr = root;
    while (curr != NULL) {
        if (curr->data > key && curr->left != NULL) {
            curr = curr->left;
        } else if (curr->data < key && curr->right != NULL) {
            curr = curr->right;
        } else {
            break;
        }
    }

    // If key is smaller, make it left
    // child, else right child
    if (curr->data > key) {
        curr->left = temp;
    } else {
        curr->right = temp;
    }

    return root;
}

// Print the tree in level order
void printTree(struct Node* root) {
    if (root == NULL) {
        printf("[]");
        return;
    }

    struct Node* q[100];
    char ans[100][10];
    int front = 0, rear = 0;
    int size = 0;

    q[rear++] = root;

    while (front < rear) {
        struct Node* curr = q[front++];

        if (curr == NULL) {
            strcpy(ans[size++], "N");
        } else {
            sprintf(ans[size++], "%d", curr->data);
            q[rear++] = curr->left;
            q[rear++] = curr->right;
        }
    }

    // Remove trailing N's
    while (size > 0 && strcmp(ans[size - 1], "N") == 0) {
        size--;
    }

    printf("[");
    for (int i = 0; i < size; i++) {
        printf("%s", ans[i]);
        if (i + 1 < size) {
            printf(", ");
        }
    }
    printf("]");
}

int main() {

    // Create the BST
    //        22
    //       /  \
    //     12    30
    //    /  \
    //   8    20
    //          \
    //           21

    struct Node* root = createNode(22);
    root->left = createNode(12);
    root->right = createNode(30);
    root->left->left = createNode(8);
    root->left->right = createNode(20);
    root->left->right->right = createNode(21);

    int key = 15;

    root = insert(root, key);

    printTree(root);

    return 0;
}
Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

// Structure for a Binary Search Tree node
class Node {
    int data;
    Node left;
    Node right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

public class Main {

    // Insert a node into the BST
    static Node insert(Node root, int key) {
        Node temp = new Node(key);

        // If tree is empty
        if (root == null) {
            return temp;
        }

        // Find the node who is going to
        // have the new node as its child
        Node curr = root;
        while (curr != null) {
            if (curr.data > key && curr.left != null) {
                curr = curr.left;
            } else if (curr.data < key && curr.right != null) {
                curr = curr.right;
            } else {
                break;
            }
        }

        // If key is smaller, make it left
        // child, else right child
        if (curr.data > key) {
            curr.left = temp;
        } else {
            curr.right = temp;
        }

        return root;
    }

    // Print the tree in level order
    static void printTree(Node root) {
        if (root == null) {
            System.out.print("[]");
            return;
        }

        ArrayList<String> ans = new ArrayList<>();
        Queue<Node> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {
            Node curr = q.poll();

            if (curr == null) {
                ans.add("N");
            } else {
                ans.add(String.valueOf(curr.data));
                q.offer(curr.left);
                q.offer(curr.right);
            }
        }

        // Remove trailing N's
        while (!ans.isEmpty() && ans.get(ans.size() - 1).equals("N")) {
            ans.remove(ans.size() - 1);
        }

        System.out.print("[");
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i));
            if (i + 1 < ans.size()) {
                System.out.print(", ");
            }
        }
        System.out.print("]");
    }

    public static void main(String[] args) {

        // Create the BST
        //        22
        //       /  \
        //     12    30
        //    /  \
        //   8    20
        //          \
        //           21

        Node root = new Node(22);
        root.left = new Node(12);
        root.right = new Node(30);
        root.left.left = new Node(8);
        root.left.right = new Node(20);
        root.left.right.right = new Node(21);

        int key = 15;

        root = insert(root, key);

        printTree(root);
    }
}
Python
from collections import deque

# Structure for a Binary Search Tree node
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Insert a node into the BST
def insert(root, key):
    temp = Node(key)

    # If tree is empty
    if root is None:
        return temp

    # Find the node who is going to
    # have the new node as its child
    curr = root
    while curr is not None:
        if curr.data > key and curr.left is not None:
            curr = curr.left
        elif curr.data < key and curr.right is not None:
            curr = curr.right
        else:
            break

    # If key is smaller, make it left
    # child, else right child
    if curr.data > key:
        curr.left = temp
    else:
        curr.right = temp

    return root

# Print the tree in level order
def printTree(root):
    if root is None:
        print("[]")
        return

    ans = []
    q = deque([root])

    while q:
        curr = q.popleft()

        if curr is None:
            ans.append("N")
        else:
            ans.append(str(curr.data))
            q.append(curr.left)
            q.append(curr.right)

    # Remove trailing N's
    while ans and ans[-1] == "N":
        ans.pop()

    print("[" + ", ".join(ans) + "]")

if __name__ == "__main__":

    # Create the BST
    #        22
    #       /  \
    #     12    30
    #    /  \
    #   8    20
    #          \
    #           21

    root = Node(22)
    root.left = Node(12)
    root.right = Node(30)
    root.left.left = Node(8)
    root.left.right = Node(20)
    root.left.right.right = Node(21)

    key = 15

    root = insert(root, key)

    printTree(root)
C#
using System;
using System.Collections.Generic;

// Structure for a Binary Search Tree node
class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GFG {

    // Insert a node into the BST
    static Node insert(Node root, int key) {
        Node temp = new Node(key);

        // If tree is empty
        if (root == null) {
            return temp;
        }

        // Find the node who is going to
        // have the new node as its child
        Node curr = root;
        while (curr != null) {
            if (curr.data > key && curr.left != null) {
                curr = curr.left;
            } else if (curr.data < key && curr.right != null) {
                curr = curr.right;
            } else {
                break;
            }
        }

        // If key is smaller, make it left
        // child, else right child
        if (curr.data > key) {
            curr.left = temp;
        } else {
            curr.right = temp;
        }

        return root;
    }

    // Print the tree in level order
    static void printTree(Node root) {
        if (root == null) {
            Console.Write("[]");
            return;
        }

        List<string> ans = new List<string>();
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {
            Node curr = q.Dequeue();

            if (curr == null) {
                ans.Add("N");
            } else {
                ans.Add(curr.data.ToString());
                q.Enqueue(curr.left);
                q.Enqueue(curr.right);
            }
        }

        // Remove trailing N's
        while (ans.Count > 0 && ans[ans.Count - 1] == "N") {
            ans.RemoveAt(ans.Count - 1);
        }

        Console.Write("[");
        for (int i = 0; i < ans.Count; i++) {
            Console.Write(ans[i]);
            if (i + 1 < ans.Count) {
                Console.Write(", ");
            }
        }
        Console.Write("]");
    }

    static void Main() {

        // Create the BST
        //        22
        //       /  \
        //     12    30
        //    /  \
        //   8    20
        //          \
        //           21

        Node root = new Node(22);
        root.left = new Node(12);
        root.right = new Node(30);
        root.left.left = new Node(8);
        root.left.right = new Node(20);
        root.left.right.right = new Node(21);

        int key = 15;

        root = insert(root, key);

        printTree(root);
    }
}
Javascript
// Structure for a Binary Search Tree node
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Insert a node into the BST
function insert(root, key) {
    let temp = new Node(key);

    // If tree is empty
    if (root === null) {
        return temp;
    }

    // Find the node who is going to
    // have the new node as its child
    let curr = root;
    while (curr !== null) {
        if (curr.data > key && curr.left !== null) {
            curr = curr.left;
        } else if (curr.data < key && curr.right !== null) {
            curr = curr.right;
        } else {
            break;
        }
    }

    // If key is smaller, make it left
    // child, else right child
    if (curr.data > key) {
        curr.left = temp;
    } else {
        curr.right = temp;
    }

    return root;
}

// Print the tree in level order
function printTree(root) {
    if (root === null) {
        console.log("[]");
        return;
    }

    const ans = [];
    const q = [root];

    while (q.length > 0) {
        const curr = q.shift();

        if (curr === null) {
            ans.push("N");
        } else {
            ans.push(curr.data.toString());
            q.push(curr.left);
            q.push(curr.right);
        }
    }

    // Remove trailing N's
    while (ans.length > 0 && ans[ans.length - 1] === "N") {
        ans.pop();
    }

    console.log("[" + ans.join(", ") + "]");
}

// Driver code

    // Create the BST
    //        22
    //       /  \
    //     12    30
    //    /  \
    //   8    20
    //          \
    //           21

    let root = new Node(22);
    root.left = new Node(12);
    root.right = new Node(30);
    root.left.left = new Node(8);
    root.left.right = new Node(20);
    root.left.right.right = new Node(21);

    let key = 15;

    root = insert(root, key);

    printTree(root);

Output
[22, 12, 30, 8, 20, N, N, N, N, 15, 21]

Related Links: 

Comment