0% found this document useful (0 votes)
3 views4 pages

Tree Traversal

This document contains a C program that implements a binary tree with functions for inserting nodes and traversing the tree in pre-order, in-order, and post-order. The program allows user interaction through a menu to perform various operations such as insertion and displaying the tree in different traversal orders. It utilizes a structure for tree nodes and includes functions for creating nodes and managing the tree structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Tree Traversal

This document contains a C program that implements a binary tree with functions for inserting nodes and traversing the tree in pre-order, in-order, and post-order. The program allows user interaction through a menu to perform various operations such as insertion and displaying the tree in different traversal orders. It utilizes a structure for tree nodes and includes functions for creating nodes and managing the tree structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Write a program to traverse the binary tree for pre-order,in-order,and

post-order.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct tnode
{
int data;
struct tnode *left, *right;
};

struct tnode *root = NULL;

struct tnode *createNode(int data)


{
struct tnode *newNode;
newNode = (struct tnode *)malloc(sizeof(struct tnode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

void insertion(struct tnode **node, int data)


{
if (!*node)
{
*node = createNode(data);
}
else if (data < (*node)->data)
{
insertion(&(*node)->left, data);
}
else if (data > (*node)->data)
{
insertion(&(*node)->right, data);
}
}

void postOrder(struct tnode *node)


{
if (node)
{
postOrder(node->left);
postOrder(node->right);
printf("%d ", node->data);
}
return;
}

void preorder(struct tnode *node)


{
if (node)
{
printf("%d ", node->data);
preorder(node->left);
preorder(node->right);
}
return;
}

void inOrder(struct tnode *node)


{
if (node)
{
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
return;
}

int main()
{
int data, ch;
clrscr();
while (1)
{
printf("\n1. Insertion\n2. Pre-order\n");
printf("3. Post-order\n4. In-order\n");
printf("5. Exit\nEnter your choice:");
scanf("%d", &ch);

switch (ch)
{
case 1:
printf("Enter your data:");
scanf("%d", &data);
insertion(&root, data);
break;
case 2:
preorder(root);
break;
case 3:
postOrder(root);
break;
case 4:
inOrder(root);
break;
case 5:
exit(0);
default:
printf("You've entered wrong option\n");
break;
}
}
getch();
return 0;
}

Output:

You might also like