Find the Size of a Binary Tree without Recursion

Objective: Given a binary tree, Write an non-recursive algorithm to find the size of the tree.

Note : Size of the tree is num­ber of nodes in the tree

Size-of-Binary-Tree-example

Size-of-Binary-Tree-example

Approach:

In our earlier post (link) we have seen the clean and simple recursive approach for finding the size of the tree. Now we will see how to solve it without recursion.

If we are not using recursion then we need a data structure to store the tree traversal, we will use queue here.

Solution is exactly similar to tree traversal without recursion. Just that we will keep counting the number of nodes.

Code:

Output:

Tree Size: 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...

  • lipsa patel

    The size of binary tree in image is “8” instead of “7”.

%d bloggers like this: