Monday, March 19, 2012

Printing the paths of a binary tree

Approach

The approach which i have to print binary tree paths is slightly different it is not the most elegant solution but I find it easy to understand so here it is. Finding whether a node is leaf or not is easy . So all you have to do is find if a node is leaf node and is it is just keep on doing getParent while getParent not equal to null push elements to stack and then just print the stack.

This way you will have the paths of all the elements in a queue.

printPath( Node n )

{
if ( Node.isLeaf()) {
pushToStack ( Node);
while ( Node.parent !=null )
{
pushToStack(Node.parent);


}
Print(PopAllFromStack());


}
else {

printPath(Node->Left);
printPath(Node->Right);


}

}


The above is a pseudo code which can easily be converted to a program in language of your choice.

No comments: