Count the number of nodes in a given binary tree

Objective: Given a binary tree, write an algorithm to count all the nodes in the tree.

Example:

Approach:

  • Do postorder traversal.
  • If the root is null return 0. (base case all well for the recursion)
  • if the root is not null then make a recursive call to the left child and right child and add the result of these with 1 ( 1 for counting the root) and return.

Code:


Output:

Number of nodes in the given binary tree: 5

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: