Inserting a key into a tree in Javascript

In a Binary Search Tree (BST), inserting a new key follows a simple rule: smaller values go to the left subtree, and larger values go to the right subtree. The first insertion creates the root node, while subsequent insertions traverse the tree to find the correct position.

How BST Insertion Works

The insertion process starts at the root and compares the new value with each node. If the value is smaller, we move left; if larger, we move right. When we reach a null position (leaf node), we insert the new node there.

Binary Search Tree Structure 10 5 15 3 7 Smaller values ? Left Larger values ? Right

Iterative Insertion Method

The iterative approach uses a while loop to traverse the tree until finding the correct insertion point:

class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

class BinarySearchTree {
    constructor() {
        this.root = null;
    }

    insertIter(data) {
        let node = new Node(data);

        // Check if the tree is empty
        if (this.root === null) {
            // Insert as the first element
            this.root = node; 
            return;
        }

        let currNode = this.root;
        while (true) {
            if (data 

Tree structure (in-order):
3
5
7
10
15

Recursive Insertion Method

The recursive approach leverages the tree's natural recursive structure. It uses a helper function to handle the recursion:

// Helper function outside the class
function insertRecHelper(root, node) {
    if (node.data 

Recursive tree structure (in-order):
3
5
7
10
12
15
50

Comparison of Methods

Method Space Complexity Readability Performance
Iterative O(1) Good Slightly faster
Recursive O(h) - height dependent Excellent Function call overhead

Key Points

  • Both methods maintain the BST property: left
  • Time complexity is O(h) where h is the tree height
  • The iterative method uses constant space, while recursive uses call stack space
  • Recursive code is more intuitive but has function call overhead

Conclusion

BST insertion can be implemented both iteratively and recursively. The iterative approach is more memory-efficient, while the recursive method is more readable and follows the tree's natural structure. Both maintain O(log n) average time complexity for balanced trees.

Updated on: 2026-03-15T23:18:59+05:30

751 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements