i) preorder traversal
ii) inorder traversal
iii) postorder traversal
This post may seem very simple . But to solve the problems related to binary trees you should have clear understanding of these traversals . For an example ,creating mirror image of the tree depends on postorder traversal .
Consider the following tree
Preorder : A B C D E F G
Inorder : C B D A F E G
Postorder : C D B F G E A
Code :(in C)
Preorder Traversal :
void preorder_traversal(struct node * node)
{
if(node!=null)
{
printf("%d ",node->data);
preorder_traversal(node->left);
preorder_traversal(node->right);
}
}
Inorder Traversal :
void inorder_traversal(struct node * node)
{
if(node!=null)
{
inorder_traversal(node->left);
printf("%d ",node->data);
inorder_traversal(node->right);
}
}
Postorder Traversal :
void postorder_traversal(struct node * node)
{
if(node!=null)
{
postorder_traversal(node->left);
postorder_traversal(node->right);
printf("%d ",node->data);
}
}
Please let me know if there is any bug in the above code and your suggestions are always welcome .
No comments:
Post a Comment