Binary Tree in Javascript

Binary Tree is a special data structure used for data storage purposes. A binary tree has a special condition that each node can have a maximum of two children. A binary tree has the benefits of both an ordered array and a linked list as search is as quick as in a sorted array and insertion or deletion operation are as fast as in the linked list.

Here is an illustration of a binary tree with some terms that we've discussed below:

A Root B C D Leaf E Leaf F Leaf Level 0 Level 1 Level 2 Path: A ? B ? D

Important Terms

Following are the important terms with respect to the tree:

  • Path - Path refers to the sequence of nodes along the edges of a tree.

  • Root - The node at the top of the tree is called root. There is only one root per tree and one path from the root node to any node.

  • Parent - Any node except the root node has one edge upward to a node called the parent.

  • Child - The node below a given node connected by its edge downward is called its child node.

  • Leaf - The node which does not have any child node is called the leaf node.

  • Subtree - Subtree represents the descendants of a node.

  • Visiting - Visiting refers to checking the value of a node when control is on the node.

  • Traversing - Traversing means passing through nodes in a specific order.

  • Levels - Level of a node represents the generation of a node. If the root node is at level 0, then its next child node is at level 1, its grandchild is at level 2, and so on.

  • Keys - Key represents a value of a node based on which a search operation is to be carried out for a node.

Binary Tree Implementation

Let's implement a simple binary tree in JavaScript with basic operations:

// Node class for binary tree
class TreeNode {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Binary Tree class
class BinaryTree {
    constructor() {
        this.root = null;
    }
    
    // Insert a new node
    insert(data) {
        const newNode = new TreeNode(data);
        
        if (this.root === null) {
            this.root = newNode;
        } else {
            this.insertNode(this.root, newNode);
        }
    }
    
    // Helper method to insert node
    insertNode(node, newNode) {
        if (newNode.data 

In-order traversal:
20
30
40
50
70

Tree Traversal Methods

There are three main ways to traverse a binary tree:

class BinaryTree {
    constructor() {
        this.root = null;
    }
    
    insert(data) {
        if (!this.root) {
            this.root = new TreeNode(data);
            return;
        }
        
        let queue = [this.root];
        while (queue.length > 0) {
            let current = queue.shift();
            
            if (!current.left) {
                current.left = new TreeNode(data);
                break;
            } else if (!current.right) {
                current.right = new TreeNode(data);
                break;
            } else {
                queue.push(current.left);
                queue.push(current.right);
            }
        }
    }
    
    // Pre-order: Root ? Left ? Right
    preOrder(node = this.root, result = []) {
        if (node) {
            result.push(node.data);
            this.preOrder(node.left, result);
            this.preOrder(node.right, result);
        }
        return result;
    }
    
    // In-order: Left ? Root ? Right
    inOrder(node = this.root, result = []) {
        if (node) {
            this.inOrder(node.left, result);
            result.push(node.data);
            this.inOrder(node.right, result);
        }
        return result;
    }
    
    // Post-order: Left ? Right ? Root
    postOrder(node = this.root, result = []) {
        if (node) {
            this.postOrder(node.left, result);
            this.postOrder(node.right, result);
            result.push(node.data);
        }
        return result;
    }
}

// Create a binary tree
const binaryTree = new BinaryTree();
binaryTree.insert(1);
binaryTree.insert(2);
binaryTree.insert(3);
binaryTree.insert(4);
binaryTree.insert(5);

console.log("Pre-order:", binaryTree.preOrder());
console.log("In-order:", binaryTree.inOrder());
console.log("Post-order:", binaryTree.postOrder());
Pre-order: [ 1, 2, 4, 5, 3 ]
In-order: [ 4, 2, 5, 1, 3 ]
Post-order: [ 4, 5, 2, 3, 1 ]

Comparison of Traversal Methods

Traversal Type Order Use Case
Pre-order Root ? Left ? Right Creating copy of tree, prefix expressions
In-order Left ? Root ? Right Getting sorted data from BST
Post-order Left ? Right ? Root Deleting tree, postfix expressions

Conclusion

Binary trees are fundamental data structures that provide efficient search, insertion, and deletion operations. Understanding tree terminology and traversal methods is essential for working with more complex tree-based algorithms and data structures.

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

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements