Count the Number of Nodes in a Complete Binary tree using JavaScript
Last Updated :
01 Jul, 2024
We need to count the number of the nodes in the complete binary tree using JavaScript. The complete binary tree is a binary tree in which every level then except possibly the last, is completely filled and all the nodes are as far left as possible.
There are several approaches for counting the number of nodes in a complete Binary tree using JavaScript which are as follows:
Using Recursion
In recursive approach, we can traverse the entire tree recursively. For the each node, we count the nodes itself plus the number of the nodes in its left subtree and the number of the nodes in its the right subtree.
Example: This illustrates a binary tree using TreeNode class instances and counts the total number of nodes in the tree using a recursive function `countNodes`, returning the count.
JavaScript
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function countNodes(root) {
if (root === null) {
return 0;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
// Example usage
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
console.log(countNodes(root)); // Output: 6
Time Complexity: O(N)
Space Complexity: O(H)
Using queue
In this approach, we use the queue to traverse the tree level by the level. We can count the each node as we dequeue it.
Example: This illustrates a binary tree using TreeNode instances, then employs an iterative approach with a queue to count all nodes in the tree, returning the total count.
JavaScript
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Example usage
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
function countNodesIterative(root) {
if (root === null) {
return 0;
}
let count = 0;
let queue = [root];
while (queue.length > 0) {
let node = queue.shift();
count++;
if (node.left !== null) {
queue.push(node.left);
}
if (node.right !== null) {
queue.push(node.right);
}
}
return count;
}
// Example usage
console.log(countNodesIterative(root));
Time Complexity: O(N)
Space Complexity: O(N)
Using while loop
In this approach, we can take the advantages of the properties of the complete binary tree. If the left and right subtrees of the node have the same height then the left subtree is the perfect binary tree. We can directly calculate the number of the nodes in the left subtree. If the heights are different, the right subtree is the perfect binary tree. This approach can reduces the number of the nodes we need to traverse.
Example: This illustrates the total number of nodes in a binary tree efficiently by leveraging the concept of perfect binary trees and recursively determining the depth of each subtree.
JavaScript
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Example usage
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
function fun(root) {
if (root === null) {
return 0;
}
let leftDepth = getDepth(root.left);
let rightDepth = getDepth(root.right);
if (leftDepth === rightDepth) {
// Left subtree is a perfect binary tree
return (1 << leftDepth) + fun(root.right);
} else {
// Right subtree is a perfect binary tree
return (1 << rightDepth) + fun(root.left);
}
}
function getDepth(node) {
let depth = 0;
while (node !== null) {
depth++;
node = node.left;
}
return depth;
}
// Example usage
console.log(fun(root));
Time Complexity: O((log N)2)
Space Complexity: O(log n)
Similar Reads
Print the nodes having exactly one child in a Binary tree using JavaScript Given a binary tree, our task is to return the number of nodes in the Binary tree that have at least one child otherwise return â-1â if no such node exists. Examples: Input: 1 / \ 2 3 / \ 4 5 / 6Output: 3Explanation:There are three nodes in the Binary tree that have at least one child that are 1,2,4
4 min read
Count the number of Nodes in a Binary Tree in Constant Space Given a binary tree having N nodes, count the number of nodes using constant O(1) space. This can be done by simple traversals like- Preorder, InOrder, PostOrder, and LevelOrder but these traversals require an extra space which is equal to the height of the tree. Examples: Input: Output: 5Explanatio
10 min read
Convert a Binary Tree to a Binary Search Tree using JavaScript Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that it keeps the original structure of the Binary Tree. Example: To demonstrate the conversion of the Binary Tree to the Binary Search Tree.Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 /
2 min read
Find the Preorder Successor of a Given Node in a Binary Tree using JavaScript The Preorder successor of a given node is a node that occurs after the given node in the preorder traversal of the binary tree. The preorder traversal is a traversal in which the root node is visited first, then the left child, and then the right child. Example: The pre-order successor of a binary t
2 min read
Check Symmetrical Binary Tree using JavaScript Given a binary tree, our task is to check whether it is Symmetrical Binary tree. In other words, we need to check whether the binary tree is a mirror of itself. Example: Input: 11 / \ 12 12 / \ / \ 13 14 14 13Output: True Input: 11 / \ 12 12 \ \ 13 13Output: FalseBelow are the approaches to check Sy
3 min read
Boundary Traversal of Binary Tree using JavaScript The Boundary Traversal of the Binary Tree can be done by traversing the left, right, and leaf parts of the Binary Tree. We will break the Boundary Traversal of Binary Tree using JavaScript in three parts. First, we will traverse the left part, right part, and leaf parts of the Binary Tree and print
4 min read
Find the maximum path sum between two leaves of a binary tree using JavaScript Given the root of a binary tree, return the maximum path sum of any non-empty path. A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to p
6 min read
JavaScript Program to Delete all Nodes of a Binary Search Tree A Binary Search Tree (BST) is a type of binary tree where each node has at most two children referred to as the left child and the right child. The value of the left child node is less than the value of the current node and the value of the right child node is greater than the value of the current n
5 min read
How to Return the Number of Images in a Document with JavaScript? We will learn how we can return the number of images in a document with JavaScript. We need to access and manipulate the DOM (Document Object Model) of the webpage. The DOM represents the structure of an HTML document as a tree of objects. JavaScript can interact with the DOM to manipulate and retri
3 min read
Javascript Program to Count 1's in a sorted binary array Given a binary array sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = {1, 1, 0, 0, 0, 0, 0} Output: 2 Input: arr[] = {1, 1, 1, 1, 1, 1, 1} Output: 7 Input: arr[] = {0, 0, 0, 0, 0, 0, 0} Output: 0A simple solution is to traverse the array linearly. The time comp
3 min read