[Naive Approach] Using DFS Traversal - O(n) Time and O(logn) Space
The simple approach to solving the given tree is to perform the DFS Traversal on the given tree and count the number of nodes in it. After traversal, print the total count of nodes obtained.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intval;Node*left;Node*right;Node(intx):val(x),left(nullptr),right(nullptr){}};// Recursively count all nodes in the treeintcountNodes(Node*root){if(root==nullptr)return0;return1+countNodes(root->left)+countNodes(root->right);}intmain(){// Build the sample treeNode*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(11);root->left->right=newNode(12);root->right->left=newNode(14);root->right->right=newNode(5);cout<<countNodes(root);return0;}
Java
// Java program to count nodes in a binary tree using recursionimportjava.util.*;classNode{intval;Nodeleft;Noderight;Node(intx){val=x;left=null;right=null;}}classGfG{// Recursively count all nodes in the treestaticintcountNodes(Noderoot){if(root==null)return0;return1+countNodes(root.left)+countNodes(root.right);}publicstaticvoidmain(String[]args){// Build the sample treeNoderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(11);root.left.right=newNode(12);root.right.left=newNode(14);root.right.right=newNode(5);System.out.println(countNodes(root));}}
Python
# Python program to count nodes in a binary tree using recursionclassNode:def__init__(self,x):self.val=xself.left=Noneself.right=None# Recursively count all nodes in the treedefcountNodes(root):ifrootisNone:return0return1+countNodes(root.left)+countNodes(root.right)# Driver codeif__name__=="__main__":# Build the sample treeroot=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(11)root.left.right=Node(12)root.right.left=Node(14)root.right.right=Node(5)print(countNodes(root))
C#
// C# program to count nodes in a binary tree using recursionusingSystem;classNode{publicintval;publicNodeleft;publicNoderight;publicNode(intx){val=x;left=null;right=null;}}classGfG{// Recursively count all nodes in the treestaticintcountNodes(Noderoot){if(root==null)return0;return1+countNodes(root.left)+countNodes(root.right);}staticvoidMain(string[]args){// Build the sample treeNoderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(11);root.left.right=newNode(12);root.right.left=newNode(14);root.right.right=newNode(5);Console.WriteLine(countNodes(root));}}
JavaScript
// JavaScript program to count nodes in a binary tree using recursionclassNode{constructor(x){this.val=x;this.left=null;this.right=null;}}// Recursively count all nodes in the treefunctioncountNodes(root){if(root===null)return0;return1+countNodes(root.left)+countNodes(root.right);}// Driver code// Build the sample treeconstroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(11);root.left.right=newNode(12);root.right.left=newNode(14);root.right.right=newNode(5);console.log(countNodes(root));
Output
7
[Expected Approach] - Optimized Recursive Approach- O((log N)2)Time and O(log N) Space
The main idea behind this approach is that a complete binary tree can have at most (2h + 1 - 1) nodes in total where h is the height of the tree (This happens when all the levels are completely filled).
By this logic, in the first case, compare the left sub-tree height with the right sub-tree height. If they are equal it is a full tree, then the answer will be 2^height - 1. Otherwise, If they aren't equal, recursively call for the left sub-tree and the right sub-tree to count the number of nodes. Follow the steps below to solve the problem:
Define a functionleft_height(root) and find the left height of the given Tree by traversing in the root's left direction and store it in a variable, say leftHeight.
Define a function right_height(root) and find the right height of the given Tree by traversing in the root's right direction and store it in a variable, say rightHeight.
Find the left and the right height of the given Tree for the current root value and if it is equal then return the value of (2height - 1) as the resultant count of nodes.
Otherwise, recursively call for the function for the left and right sub-trees and return the sum of them + 1 as the resultant count of nodes.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intval;Node*left;Node*right;Node(intx):val(x),left(nullptr),right(nullptr){}};// Height obtained by moving only to the leftintleftHeight(Node*root){inth=0;while(root){h++;root=root->left;}returnh;}// Height obtained by moving only to the rightintrightHeight(Node*root){inth=0;while(root){h++;root=root->right;}returnh;}// Count nodes using complete binary tree propertyintcountNodes(Node*root){if(root==nullptr)return0;intlh=leftHeight(root);intrh=rightHeight(root);// Perfect binary treeif(lh==rh)return(1<<lh)-1;return1+countNodes(root->left)+countNodes(root->right);}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(11);root->left->right=newNode(12);root->right->left=newNode(14);root->right->right=newNode(5);cout<<countNodes(root);return0;}
Java
// Java program to count nodes in a complete binary treeimportjava.util.*;classNode{intval;Nodeleft;Noderight;Node(intx){val=x;left=null;right=null;}}classGfG{// Height obtained by moving only to the leftstaticintleftHeight(Noderoot){inth=0;while(root!=null){h++;root=root.left;}returnh;}// Height obtained by moving only to the rightstaticintrightHeight(Noderoot){inth=0;while(root!=null){h++;root=root.right;}returnh;}// Count nodes using complete binary tree propertystaticintcountNodes(Noderoot){if(root==null)return0;intlh=leftHeight(root);intrh=rightHeight(root);// Perfect binary treeif(lh==rh)return(1<<lh)-1;return1+countNodes(root.left)+countNodes(root.right);}publicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(11);root.left.right=newNode(12);root.right.left=newNode(14);root.right.right=newNode(5);System.out.println(countNodes(root));}}nodeNode=newnode();Node.data=data;Node.left=null;Node.right=null;return(Node);}// Driver Codepublicstaticvoidmain(String[]args){noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(11);root.left.right=newNode(12);root.right.left=newNode(14);root.right.right=newNode(5);System.out.print(TotalNodes(root));}}
Python
# Python program to count nodes in a complete binary treeclassNode:def__init__(self,x):self.val=xself.left=Noneself.right=None# Height obtained by moving only to the leftdefleftHeight(root):h=0whileroot:h+=1root=root.leftreturnh# Height obtained by moving only to the rightdefrightHeight(root):h=0whileroot:h+=1root=root.rightreturnh# Count nodes using complete binary tree propertydefcountNodes(root):ifrootisNone:return0lh=leftHeight(root)rh=rightHeight(root)# Perfect binary treeiflh==rh:return(1<<lh)-1return1+countNodes(root.left)+countNodes(root.right)# Driver codeif__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(11)root.left.right=Node(12)root.right.left=Node(14)root.right.right=Node(5)print(countNodes(root))
C#
// C# program to count nodes in a complete binary treeusingSystem;classNode{publicintval;publicNodeleft;publicNoderight;publicNode(intx){val=x;left=null;right=null;}}classGfG{// Height obtained by moving only to the leftstaticintleftHeight(Noderoot){inth=0;while(root!=null){h++;root=root.left;}returnh;}// Height obtained by moving only to the rightstaticintrightHeight(Noderoot){inth=0;while(root!=null){h++;root=root.right;}returnh;}// Count nodes using complete binary tree propertystaticintcountNodes(Noderoot){if(root==null)return0;intlh=leftHeight(root);intrh=rightHeight(root);// Perfect binary treeif(lh==rh)return(1<<lh)-1;return1+countNodes(root.left)+countNodes(root.right);}staticvoidMain(string[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(11);root.left.right=newNode(12);root.right.left=newNode(14);root.right.right=newNode(5);Console.WriteLine(countNodes(root));}}
JavaScript
// JavaScript program to count nodes in a complete binary treeclassNode{constructor(x){this.val=x;this.left=null;this.right=null;}}// Height obtained by moving only to the leftfunctionleftHeight(root){leth=0;while(root){h++;root=root.left;}returnh;}// Height obtained by moving only to the rightfunctionrightHeight(root){leth=0;while(root){h++;root=root.right;}returnh;}// Count nodes using complete binary tree propertyfunctioncountNodes(root){if(root===null)return0;constlh=leftHeight(root);constrh=rightHeight(root);// Perfect binary treeif(lh===rh)return(1<<lh)-1;return1+countNodes(root.left)+countNodes(root.right);}// Driver codeconstroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(11);root.left.right=newNode(12);root.right.left=newNode(14);root.right.right=newNode(5);console.log(countNodes(root));