Learn basic concept of c , c++ and python programming in regularcodes.com

Spread the post

Find the height of a binary tree without recursion

Count height of given binary tree without using recursive method. simplest method are using a queue.

For example Given Binary tree are contain following nodes.

12475836910

calculate height of a binary tree iterative are : [4]

View pointers and nodes of tree.

Stack Areamainhead(pointer) NULLroot(pointer)tail(pointer) NULL Heap Areastruct Treedata (int)= 1left (pointer) right (pointer) struct Treedata (int)= 2left (pointer) right (pointer) struct Treedata (int)= 3left (pointer)= NULLright (pointer) struct Treedata (int)= 4left (pointer) right (pointer)= NULLstruct Treedata (int)= 5left (pointer)= NULLright (pointer) struct Treedata (int)= 6left (pointer) right (pointer)= NULLstruct Treedata (int)= 7left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 8left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 9left (pointer)= NULLright (pointer) struct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULL

height of a binary tree are the longest path between root to leaf node.

12475836910

Try it Yourself

C program for height of binary tree without recursion. Time complexity O(n).


Output

View process

Stack Areamainhead(pointer)root(pointer)tail(pointer)tree_heightheight (int) =3temp(pointer) Heap Areastruct Treedata (int)= 1left (pointer) right (pointer) struct Treedata (int)= 2left (pointer) right (pointer) struct Treedata (int)= 3left (pointer)= NULLright (pointer) struct Treedata (int)= 4left (pointer) right (pointer)= NULLstruct Treedata (int)= 5left (pointer)= NULLright (pointer) struct Treedata (int)= 6left (pointer) right (pointer)= NULLstruct Treedata (int)= 7left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 8left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 9left (pointer)= NULLright (pointer) struct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULLstruct Queuelevel (int)= 0link (pointer) next (pointer) struct Queuelevel (int)= 1link (pointer) next (pointer) struct Queuelevel (int)= 1link (pointer) next (pointer) struct Queuelevel (int)= 2link (pointer) next (pointer) struct Queuelevel (int)= 2link (pointer) next (pointer) struct Queuelevel (int)= 2link (pointer) next (pointer) struct Queuelevel (int)= 3link (pointer) next (pointer) struct Queuelevel (int)= 3link (pointer) next (pointer) struct Queuelevel (int)= 3link (pointer) next (pointer) struct Queuelevel (int)= 4link (pointer) next (pointer)= NULL

Try it Yourself

Spread the post

Recommended Posts: