Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Find the Size of a Binary Tree without Recursion

Objec­tive: Given a binary tree, Write an non-recursive algo­rithm 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 ear­lier post (link) we have seen the clean and sim­ple recur­sive approach for find­ing the size of the tree. Now we will see how to solve it with­out recursion.

If we are not using recur­sion then we need a data struc­ture to store the tree tra­ver­sal, we will use queue here.

Solu­tion is exactly sim­i­lar to tree tra­ver­sal with­out recur­sion. Just that we will keep count­ing the num­ber of nodes.

Code:

Out­put:

Tree Size: 5

You may also like...