Spread the post

Print leftmost nodes of a Binary Tree

Given a binary tree, print leftmost nodes of this tree. Write an efficient algorithm to solve this problem.

Example

9010807720506030

View Binary tree nodes.

Stack Areamainhead(pointer) NULLroot(pointer)tail(pointer) NULL Heap Areastruct Treedata (int)= 90left (pointer) right (pointer) struct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 80left (pointer) right (pointer) struct Treedata (int)= 77left (pointer) right (pointer) struct Treedata (int)= 60left (pointer)= NULLright (pointer) struct Treedata (int)= 30left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 50left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 20left (pointer)= NULLright (pointer)= NULL

View RightMost nodes

9010807720506030

We are easily solve this problem using queue.

logical steps:
1) Insert all binary tree nodes into queue. in level order.
2) Inserted queue nodes are providing the height of every nodes. because this height are compared binary tree level.
3) level order traversal of a this queue. and if find new level then print that first nodes of this level. view this last spets using function.

Code implementation

Output

Stack Areamainhead(pointer)root(pointer)tail(pointer)left_mosttemp(pointer) NULL Heap Areastruct Treedata (int)= 90left (pointer) right (pointer) struct Treedata (int)= 10left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 80left (pointer) right (pointer) struct Treedata (int)= 77left (pointer) right (pointer) struct Treedata (int)= 60left (pointer)= NULLright (pointer) struct Treedata (int)= 30left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 50left (pointer)= NULLright (pointer)= NULLstruct Treedata (int)= 20left (pointer)= NULLright (pointer)= NULLstruct Queueheight (int)= 0link (pointer) next (pointer) struct Queueheight (int)= 1link (pointer) next (pointer) struct Queueheight (int)= 1link (pointer) next (pointer) struct Queueheight (int)= 2link (pointer) next (pointer) struct Queueheight (int)= 2link (pointer) next (pointer) struct Queueheight (int)= 3link (pointer) next (pointer) struct Queueheight (int)= 3link (pointer) next (pointer) struct Queueheight (int)= 3link (pointer) next (pointer)= NULL

View steps of execution

Submit your solution in comment section.

Spread the post

Recommended Posts: