Tree Traversal

From Ta Wiki
Jump to navigation Jump to search
#include<stdio.h>
#include<stdlib.h>
struct node{
    char val;
    node *l,*r;
};
void pre(node *root){
    printf("%c",root->val);
    if(root->l!=NULL) pre(root->l);
    if(root->r!=NULL) pre(root->r);
}
void post(node *root){
    if(root->l!=NULL) post(root->l);
    if(root->r!=NULL) post(root->r);
    printf("%c",root->val);
}
void in(node *root){
    if(root->l!=NULL) in(root->l);
    printf("%c",root->val);
    if(root->r!=NULL) in(root->r);
}
void bfs(node *root){
    node *queue[100],*tmp;
    int front=0,back=0;
    queue[back]=root;
    back++;
    while(front!=back){
        tmp=queue[front];
        front++;
        if(tmp->l!=NULL){
            queue[back]=tmp->l;
            back++;
        }
        if(tmp->r!=NULL){
            queue[back]=tmp->r;
            back++;
        }
        printf("%c",tmp->val);
    }
}
int main(){
    node *root;
    
    root=(node*)malloc(sizeof(node));
    root->val='+';
    
    root->l=(node*)malloc(sizeof(node));
    root->l->val='/';
    
    root->r=(node*)malloc(sizeof(node));
    root->r->val='*';
    
    root->l->l=(node*)malloc(sizeof(node));
    root->l->l->val='*';
    
    root->l->r=(node*)malloc(sizeof(node));
    root->l->r->val='-';
    
    root->r->l=(node*)malloc(sizeof(node));
    root->r->l->val='5';
    root->r->l->l=NULL;
    root->r->l->r=NULL;
    
    root->r->r=(node*)malloc(sizeof(node));
    root->r->r->val='-';
    
    root->l->l->l=(node*)malloc(sizeof(node));
    root->l->l->l->val='2';
    root->l->l->l->l=NULL;
    root->l->l->l->r=NULL;
    
    root->l->l->r=(node*)malloc(sizeof(node));
    root->l->l->r->val='3';
    root->l->l->r->l=NULL;
    root->l->l->r->r=NULL;
    
    root->l->r->l=(node*)malloc(sizeof(node));
    root->l->r->l->val='2';
    root->l->r->l->l=NULL;
    root->l->r->l->r=NULL;
    
    root->l->r->r=(node*)malloc(sizeof(node));
    root->l->r->r->val='1';
    root->l->r->r->l=NULL;
    root->l->r->r->r=NULL;
    
    root->r->r->l=(node*)malloc(sizeof(node));
    root->r->r->l->val='4';
    root->r->r->l->l=NULL;
    root->r->r->l->r=NULL;
    
    root->r->r->r=(node*)malloc(sizeof(node));
    root->r->r->r->val='1';
    root->r->r->r->l=NULL;
    root->r->r->r->r=NULL;
    
    printf("\n");
    printf("PRE  ORDER TRAVERSAL : ");
    pre(root);
    printf("\n");
    printf("POST ORDER TRAVERSAL : ");
    post(root);
    printf("\n");
    printf("IN   ORDER TRAVERSAL : ");
    in(root);
    printf("\n");
    printf("BREADTH FIRST SEARCH : ");
    bfs(root);
    printf("\n");
    
    scanf(" ");
    return 0;
}