Traversal in BST

Binary Search Tree - Traversal inorder , preorder and  postorder

Sample input : 30 20 40 70 60 80
Sample output : Preorder  : 30 20 60 80 70 40
                          Inorder    :  20 30 40 60 70 80
                          Postorder :  20 60 80 7040 30

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
struct node
{
    int data;
    struct node *left;
    struct node *right;
};
struct node *newNode,*root,*prev,*tptr;
void addNode(int data) 
{
    newNode=(struct node *)malloc(sizeof(struct node));
    newNode->data=data;
    newNode->left=NULL;
    newNode->right=NULL;
    if(root==NULL) //add root node if tree is empty 
        root=newNode;
    else   //add node in left or right to root
    {   
        for(prev=NULL,tptr=root;tptr;prev=tptr,tptr=(tptr->data < newNode->data) ? (tptr->right):(tptr->left));
        if(prev->data < newNode->data)
            prev->right=newNode;
        else
            prev->left=newNode;
    }
} 
void preOrder(struct node *travptr) //preorder traversal 
{
    if(travptr==NULL)
        return;
    printf("%d  ",travptr->data);
    postOrder(travptr->left);
    postOrder(travptr->right);
}

void inOrder(struct node *travptr) //inorder traversal
{
    if(travptr==NULL)
        return;
    inOrder(travptr->left);
    printf("%d  ",travptr->data);
    inOrder(travptr->right);
}
void postOrder(struct node *travptr) //postOrder traversal
{
    if(travptr==NULL)
        return;
    postOrder(travptr->left);
    postOrder(travptr->right);
    printf("%d  ",travptr->data);
}
int main()
{
    addNode(30);
    addNode(20);
    addNode(40);
    addNode(70);
    addNode(60);
    addNode(80);
    printf("PREORDER :  ");
    preOrder(root);
    printf("\nINORDER  :  ");
    inOrder(root);
    printf("\nPOSTORDER : ");
    postOrder(root);
    return 0;
}

OUTPUT :


0 comments