Binary trees can be traversed by three simple methods. That are:
1) In-order
2) Pre-order
3) Post- order
More on tree traversal
1) In-order
2) Pre-order
3) Post- order
More on tree traversal
To traverse a non-empty binary tree in inorder (symmetric), perform the following operations recursively at each node:
- Traverse the left subtree.
- Visit the root.
- Traverse the right subtree.
To traverse a non-empty binary tree in preorder, perform the following operations recursively at each node, starting with the root node:
- Visit the root.
- Traverse the left subtree.
- Traverse the right subtree.
To traverse a non-empty binary tree in postorder, perform the following operations recursively at each node:
- Traverse the left subtree.
- Traverse the right subtree.
- Visit the root.
C program below illustrates three of the traversal carefully :-
struct node {
struct node *left;
int data;
struct node *right;
};
void insert(struct node **p, int n) {
if(*p == NULL) {
*p = (struct node*) malloc(sizeof(struct node));
(*p)->left = NULL;
(*p)->data = n;
(*p)->right = NULL;
}
else {
if(n < (*p)->data)
insert(&((*p)->left), n);
else
insert(&((*p)->right), n);
}
}
void inorder(struct node* p) {
if(p != NULL) {
inorder(p->left);
printf("%d ",p->data);
inorder(p->right);
}
}
void preorder(struct node* p) {
if(p != NULL) {
printf("%d ",p->data);
preorder(p->left);
preorder(p->right);
}
}
void postorder(struct node* p) {
if(p != NULL) {
postorder(p->left);
postorder(p->right);
printf("%d ",p->data);
}
}
int main() {
struct node *bt = NULL;
int t,n,i=0;
scanf("%d",&t);
while(t--) {
scanf("%d",&n);
insert(&bt, n);
//Address to the pointer is passed to
//retain the value of root node.
}
printf("In-order is:\n");
inorder(bt);
printf("\nPre-order is:\n");
preorder(bt);
printf("\nPost-order is:\n");
postorder(bt);
return 0;
}