[Expected Approach] - By using Recursion - O(n) Time and O(h) Auxiliary Space
The idea is to recursively calculate the size of tree. For each node (starting from root node), calculate the size of left subtree and right subtree and return the size of current subtree (size of left subtree + size of right subtree + 1).
Consider the following tree for example to understand the flow.
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Recursive function to find the// size of binary tree.intgetSize(Node*root){if(root==nullptr)return0;// Find the size of left and right// subtree.intleft=getSize(root->left);intright=getSize(root->right);// return the size of curr subtree.returnleft+right+1;}intmain(){// Constructed binary tree is// 5// / \ // 1 6// / / \ // 3 7 4Node*root=newNode(5);root->left=newNode(1);root->right=newNode(6);root->left->left=newNode(3);root->right->left=newNode(7);root->right->right=newNode(4);cout<<getSize(root)<<endl;return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Recursive function to find the// size of binary tree.intgetSize(structNode*root){if(root==NULL)return0;// Find the size of left and right// subtree.intleft=getSize(root->left);intright=getSize(root->right);// return the size of curr subtree.returnleft+right+1;}// Function to create NodestructNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=NULL;newNode->right=NULL;returnnewNode;}intmain(){// Constructed binary tree is// 5// / \ // 1 6// / / \ // 3 7 4structNode*root=createNode(5);root->left=createNode(1);root->right=createNode(6);root->left->left=createNode(3);root->right->left=createNode(7);root->right->right=createNode(4);printf("%d\n",getSize(root));return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Recursive function to find the// size of binary tree.staticintgetSize(Noderoot){if(root==null)return0;// Find the size of left and right// subtree.intleft=getSize(root.left);intright=getSize(root.right);// return the size of curr subtree.returnleft+right+1;}publicstaticvoidmain(String[]args){// Constructed binary tree is// 5// / \// 1 6// / / \// 3 7 4Noderoot=newNode(5);root.left=newNode(1);root.right=newNode(6);root.left.left=newNode(3);root.right.left=newNode(7);root.right.right=newNode(4);System.out.println(getSize(root));}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Recursive function to find the# size of binary tree.defgetSize(root):ifrootisNone:return0# Find the size of left and right# subtree.left=getSize(root.left)right=getSize(root.right)# return the size of curr subtree.returnleft+right+1if__name__=="__main__":# Constructed binary tree is# 5# / \# 1 6# / / \# 3 7 4root=Node(5)root.left=Node(1)root.right=Node(6)root.left.left=Node(3)root.right.left=Node(7)root.right.right=Node(4)print(getSize(root))
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Recursive function to find the// size of binary tree.staticintgetSize(Noderoot){if(root==null)return0;// Find the size of left and right// subtree.intleft=getSize(root.left);intright=getSize(root.right);// return the size of curr subtree.returnleft+right+1;}staticvoidMain(string[]args){// Constructed binary tree is// 5// / \// 1 6// / / \// 3 7 4Noderoot=newNode(5);root.left=newNode(1);root.right=newNode(6);root.left.left=newNode(3);root.right.left=newNode(7);root.right.right=newNode(4);Console.WriteLine(getSize(root));}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Recursive function to find the// size of binary tree.functiongetSize(root){if(root===null)return0;// Find the size of left and right// subtree.letleft=getSize(root.left);letright=getSize(root.right);// return the size of curr subtree.returnleft+right+1;}// Constructed binary tree is// 5// / \// 1 6// / / \// 3 7 4letroot=newNode(5);root.left=newNode(1);root.right=newNode(6);root.left.left=newNode(3);root.right.left=newNode(7);root.right.right=newNode(4);console.log(getSize(root));
Output
6
[Alternate Approach] - Using Breadth First Search(BFS) - O(n) Time and O(n) Space
The idea is to traverse the tree level by level using a queue. Start from the root node, and for each node, visit it, increment the count, and add its left and right children to the queue. Continue this process until all nodes are visited. The total count at the end gives the size of the tree.
Dry run for the below tree structure:
Let us see all iterations of the main loop for the above tree.
Iter 1: Queue = [5], Pop = 5 and Count = 1 then Push = [1, 6]
Iter 2: Queue = [1, 6], Pop = 1 and Count = 2 then Push = [6, 3]
Iter 3: Queue = [6, 3], Pop = 6 and Count = 3 then Push = [3, 7, 4]
Iter 4: Queue = [3, 7, 4], Pop = 3 and Count = 4 then Push = [7,4]
Iter 5: Queue = [7,4], Pop = 7 and Count = 5 then Push = [4]
Iter 6: Queue = [4], Pop = 4 and Count = 6 then Push = []
Final answer is total nodes = 6.
C++
#include<iostream>usingnamespacestd;// Define Node classclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=NULL;right=NULL;}};// BFS function to count nodesintbfs(Node*root){intcnt=0;// Create queue and push rootqueue<Node*>pq;pq.push(root);while(!pq.empty()){// Remove front node and increment countNode*node=pq.front();pq.pop();cnt+=1;// Add left childif(node->left){pq.push(node->left);}// Add right childif(node->right){pq.push(node->right);}}returncnt;}// Function to get size of the treeintgetSize(Node*root){if(root==NULL){return0;}returnbfs(root);}// Main functionintmain(){// Constructed binary tree is// 5// / \ // 1 6// / / \ // 3 7 4Node*root=newNode(5);root->left=newNode(1);root->right=newNode(6);root->left->left=newNode(3);root->right->left=newNode(7);root->right->right=newNode(4);cout<<getSize(root)<<endl;return0;return0;}
C
#include<stdio.h>#include<stdlib.h>#define N 100000// Define Node structurestructNode{intdata;structNode*left;structNode*right;};// Function to create a new nodestructNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=NULL;newNode->right=NULL;returnnewNode;}// Simple queue implementation using arraystructNode*queue[N];intfront=0,rear=0;// Enqueue operationvoidenqueue(structNode*node){queue[rear++]=node;}// Dequeue operationstructNode*dequeue(){returnqueue[front++];}// Check if queue is emptyintisEmpty(){returnfront==rear;}// BFS function to count nodesintbfs(structNode*root){intcnt=0;// Push root node into queueenqueue(root);while(!isEmpty()){// Remove front node and increment countstructNode*node=dequeue();cnt++;// Add left childif(node->left)enqueue(node->left);// Add right childif(node->right)enqueue(node->right);}returncnt;}// Function to get size of treeintgetSize(structNode*root){if(root==NULL)return0;returnbfs(root);}intmain(){// Constructed binary tree is// 5// / \ // 1 6// / / \ // 3 7 4structNode*root=createNode(5);root->left=createNode(1);root->right=createNode(6);root->left->left=createNode(3);root->right->left=createNode(7);root->right->right=createNode(4);printf("%d\n",getSize(root));return0;}
Java
importjava.util.*;// Define Node classclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}publicclassMain{// BFS function to count nodesstaticintbfs(Noderoot){intcnt=0;// Create queue and push rootQueue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){// Remove front node and increment countNodenode=q.poll();cnt++;// Add left child if not nullif(node.left!=null)q.add(node.left);// Add right child if not nullif(node.right!=null)q.add(node.right);}returncnt;}// Function to get size of the treestaticintgetSize(Noderoot){if(root==null)return0;returnbfs(root);}// Main functionpublicstaticvoidmain(String[]args){// Constructed binary tree is// 5// / \// 1 6// / / \// 3 7 4Noderoot=newNode(5);root.left=newNode(1);root.right=newNode(6);root.left.left=newNode(3);root.right.left=newNode(7);root.right.right=newNode(4);System.out.println(getSize(root));}}
Python
fromcollectionsimportdeque# Define Node classclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# BFS function for count nodesdefbfs(root):cnt=0# Create queue and push rootq=deque()q.append(root)whileq:# Remove front node and increment countnode=q.popleft()cnt+=1# Add left childifnode.left:q.append(node.left)# Add right childifnode.right:q.append(node.right)returncnt# Function to get size of the treedefgetSize(root):ifrootisNone:return0returnbfs(root)# Driver codeif__name__=="__main__":# Constructed binary tree is# 5# / \# 1 6# / / \# 3 7 4root=Node(5)root.left=Node(1)root.right=Node(6)root.left.left=Node(3)root.right.left=Node(7)root.right.right=Node(4)print(getSize(root))
C#
usingSystem;usingSystem.Collections.Generic;// Define Node classclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classProgram{// BFS function to count nodesstaticintbfs(Noderoot){intcnt=0;// Create queue and push rootQueue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){// Remove front and increment countNodenode=q.Dequeue();cnt++;// Add left childif(node.left!=null)q.Enqueue(node.left);// Add right childif(node.right!=null)q.Enqueue(node.right);}returncnt;}// Function to get size of the nodestaticintgetSize(Noderoot){if(root==null)return0;returnbfs(root);}// Main functionstaticvoidMain(){// Constructed binary tree is// 5// / \// 1 6// / / \// 3 7 4Noderoot=newNode(5);root.left=newNode(1);root.right=newNode(6);root.left.left=newNode(3);root.right.left=newNode(7);root.right.right=newNode(4);Console.WriteLine(getSize(root));}}
JavaScript
// Define Node classclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// BFS function to count nodesfunctionbfs(root){letcnt=0;// Create queue and push rootletq=[];q.push(root);while(q.length>0){// Remove front and increment countletnode=q.shift();cnt++;// Add left childif(node.left)q.push(node.left);// Add right childif(node.right)q.push(node.right);}returncnt;}// Function to get size of the treefunctiongetSize(root){if(root===null)return0;returnbfs(root);}// Driver code// Constructed binary tree is// 5// / \// 1 6// / / \// 3 7 4letroot=newNode(5);root.left=newNode(1);root.right=newNode(6);root.left.left=newNode(3);root.right.left=newNode(7);root.right.right=newNode(4);console.log(getSize(root));