Table of contents
1.
🎪Introduction
2.
🎪Definition of a Binary Tree Node
3.
🎪Binary Tree Basic Traversals
3.1.
🎨Inorder Traversal
3.2.
🎨Postorder Traversal
3.3.
🎨Preorder Traversal
4.
🎪Valid Binary Search Tree
5.
🎪Finding Binary Tree Max Depth
6.
🎪Finding the Lowest Common Ancestor Between Two Tree Nodes
6.1.
Refer to the following video for more details on Binary Tree in Javascript:
7.
Frequently Asked Questions
7.1.
Binary Tree in JavaScript, what does a binary tree mean?
7.2.
What distinguishes the binary tree from the BST?
7.3.
Describe Binary Search Trees.
7.4.
What are the uses of a binary tree?
8.
Conclusion
Last Updated: Aug 13, 2025

Introduction to Binary Tree in Javascript

Author Kumar Saurav
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

🎪Introduction

The BST resembles a tree with a single root at the top. Their ordered design enables quick searches and lookups, so they are perfect for storing numerical numbers.

The characteristics of BST are as follows as compared to a typical tree:

  • Every left child's value is lower than that of its parent.
     
  • Every right child has a value greater than that of its parent.
     
  • Every node has a child capacity of 0 to 2.
     
BINARY TREE


Also See, Interpolation in Angular

🎪Definition of a Binary Tree Node

In Javascript, we often define a Binary Tree Node with the following function:

function TreeNode(val, left, right) 
{
     this.val = val
     this.left = left
     this.right = right
}

🎪Binary Tree Basic Traversals

Understanding how to loop around each BST node is the first thing to learn. It enables us to execute a function across all BST nodes. 

There are mainly three methods for doing this. 

  1. Inorder Traversal
     
  2. Postorder Traversal
     
  3. Preorder Traversal
TRAVERSALS

🎨Inorder Traversal

The most straightforward technique to start with a binary tree, “Inorder Traversal,” is via a recursive algorithm. Here's the concept:

  • Recursively call the node's left child function until the node is not null.
     
  • Once you have gone through all the left children, perform the required operations on the node. In this case, print the node. The leftmost node will always be our current node.
     
  • Finally, call the node's right child.
     

The Inorder algorithm walks through the tree nodes from the left to the middle to the right.

INORDER

Inorder: 4,2,1,7,5,8,3,6

const inorder = (root) => 
{
    const nodes = []
    if (root) 
    {
        inorder(root.left)
        nodes.push(root.val)
        inorder(root.right)
    }
    return nodes
}


In the above code, we are recursively going towards the leftmost element of the binary tree. Then print all the root nodes one by one. Then moving towards the right node. This recursive call will print the “Inorder Traversal” of the binary tree in Javascript.

Time Complexity: O(n), where 'n' is the size of the binary tree.

Space Complexity: O(h), where ‘h’ is the height of the binary tree.

🎨Postorder Traversal

  • Recursively call the node's left child function until the node is not null. 
     
  • Call the function on ‘node.right’ when there are no longer any children left.
     
  • Finally, perform the required node operations.
     

Postorder visits the tree nodes from left to right to the middle.

POSTORDER

Postorder: 4,2,7,8,5,6,3,1

const postorder = (root) =>
{
    const nodes = []
    if (root) 
    {
        postorder(root.left)
        postorder(root.right)
        nodes.push(root.val)
    }
    return nodes
}


In the above code, we are recursively going towards the leftmost element of the binary tree. Then print the rightmost element of that particular node using recursion at all nodes. This recursive call will print the “Postorder Traversal” of the binary tree in Javascript.

Time Complexity: O(n), where 'n' is the size of the binary tree.

Space Complexity: O(h), where ‘h’ is the height of the binary tree.

🎨Preorder Traversal

  • If the node is null, do nothing; if not, perform some action on it.
     
  • Repeat the process by moving to the node's left child.
     
  • Similarly, repeat the traversal for the right child of the node.
     

The tree nodes in postorder traversal are visited from the middle to the left to the right.

PREORDER

Preorder: 1,2,4,3,5,7,8,6

const preorder = (root) => 
{
    const nodes = []
    if (root) 
    {
        nodes.push(root.val)
        preorder(root.left)
        preorder(root.right)
    }
    return nodes
}


In the above code, we first print the root value and then do a left and right traversal, respectively, using recursion at all nodes. This recursive call will print the “Preorder Traversal” of the binary tree in Javascript.

Time complexity: O(n), where 'n' is the size of the binary tree.

Space complexity: O(h), where ‘h’ is the height of the binary tree.

🎪Valid Binary Search Tree

All left children of a valid binary search tree (BST) have values lower than the parent node, and all right children have values higher than the parent node.

To check whether a tree is a legitimate Binary Search Tree:

  • Set the minimum and maximum values that the current node may have.
     
  • Return false if a node's value is outside of those boundaries.
     
  • Validate the node's left children iteratively with the node's value as the maximum bound.
     
  • Validate the right children of the node iteratively with the minimum bound fixed to the node's value.
VALID BINARY SEARCH
const isValidBST = (root) => 
{
    const helper = (node, Min, Max) => 
    {
        if (!node) return true
        if (node.val <= Min || node.val >= Max) return false
        return helper(node.left, Min, node.val) && helper(node.right, node.val, Max)
    }
    return helper(root, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)
}

🎪Finding Binary Tree Max Depth

The algorithm attempts to determine the height and depth of our BST in this case. In other words, we examine the number of "levels" a BST has.

  • Return 0 if the node is null, as it does not contribute in depth.
     
  • If not, increase our depth by one.
     
  • Calculate the depth of a node's children iteratively and return the highest value between the left and right subtree's depth.
MAX DEPTH
const maxDepth = function(root) 
{
    const Cal = (node) => 
    {
        if (!node) 
        	return 0
        return Math.max(1 + Cal(node.left), 1 + Cal(node.right))
    }
    return Cal(root)
}

 

Must Read Recursive Binary Search.

🎪Finding the Lowest Common Ancestor Between Two Tree Nodes

Increase the level of difficulty. How can we determine the binary tree's common ancestor between two tree nodes? Let's examine a few instances.

LOWEST COMMON ANCESTOR

The lowest common ancestor between 3 and 1 in this tree is 2. LCA of 3 and 2 equals 2. The LCA of 6 and 1 is equal to 4.

📝Do you see a pattern here? 

A parent node with the first child located somewhere in its left subtree and the second child located somewhere in its right subtree is the LCA between two tree nodes. This is the case for 3 and 2.

The following formula is used to determine the LCA between two nodes, p and q:

  • Check whether p or q is present in the left or right subtree.
     
  • Next, confirm whether the current node is p or q.
     
  • If one of p or q is the node itself, we will find the LCA if one of p or q is present in the left or right subtree.
     
  • We have discovered the LCA if p and q are located in either the left or right subtree.
     
const lowestCommonAncestor = function(root, p, q) 
{
    let LCA = null
    const isCommonPath = (node) => 
    {
        if (!node) return false
        var isLeft = isCommonPath(node.left)
        var isRight = isCommonPath(node.right)
        var isMid = node == p || node == q
        if (isMid && isLeft || isMid && isRight || isLeft && isRight) 
        {
            LCA = node
        }
        return isLeft || isRight || isMid
    }
    isCommonPath(root)
    return LCA
}

Refer to the following video for more details on Binary Tree in Javascript:

You can also read about mock interview.

Frequently Asked Questions

Binary Tree in JavaScript, what does a binary tree mean?

A group of connected nodes representing a hierarchical tree structure makes up a binary tree, a type of data structure.

What distinguishes the binary tree from the BST?

A non-linear type of data structure known as a "Binary Tree" has nodes that can have 2, 1, or 0 nodes. A right pointer, a left pointer, and the data element make up each node. Another ordered and physically organized Binary Tree is the BST or Binary Search Tree.

Describe Binary Search Trees.

We can easily maintain a sorted list of numbers using the data structure known as a binary search tree. Each tree node can have a maximum of two offspring, hence the name "binary tree." The fact that it may be used to search for the presence of a number in O(log(n)) time gives it the name "search tree."

What are the uses of a binary tree?

Due to their ability to store data hierarchically, binary trees are primarily used in computing for searching and sorting. Insertion, deletion, and traversal are some frequent operations that can be performed on binary trees.

Conclusion

The article “Binary Tree in Javascript” discussed the Binary Tree In Javascript. We have seen all three types of traversals. Then we discussed how to check if a tree is a valid Binary Tree. 

We also learned how to find the Depth of a Binary Tree in Javascript. At last, we discussed how to find the lowest common ancestor between two Binary Tree in Javascript Nodes.

Recommended Readings:

Recommended problems -

 

You can refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, Javascript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.
Happy learning!

Live masterclass