There are 3 basic ways to traverse a Binary TREE:-
a) PreOder
b) InOrder
c) PostOrder
And,its very easy to define them recursively
PreOrder:-
a)Visit the Root
b)Visit the Left Sub tree in PreOrder
c)Visit the Right Sub tree in Preorder.
Same can be done for InOrder and Postorder where Root is visited at stage b) and stage c) respectively.
Here is a sample code
PreOrder ( Tree tree){
if(tree!=null){
printf(tree->info);
PreOrder(tree->left);
PreOrder(tree->right);
}
}
Writing recursive definition is easy,
writing iterative version is bit tricky.
You can find the iterative version of all three here. I have posted them at code.google.com.
Feel free to use it and send me your suggestion/comments/feedback.
Cheers,
Kapil Dalwani
No comments:
Post a Comment