0% found this document useful (0 votes)
4 views7 pages

BINARY PROGRAM

Write a program to traverse the binary tree for pre-order, in-order, and post-order
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)
4 views7 pages

BINARY PROGRAM

Write a program to traverse the binary tree for pre-order, in-order, and post-order
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/ 7

PROGRAM -3

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

#include <stdio.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);
}
}
/* post order tree traversal */
void postOrder(struct tnode *node)
{
if (node)
{
postOrder(node->left);
postOrder(node->right);
printf("%d ", node->data);
}
return;
}
/* pre order tree traversal */
void preOrder(struct tnode *node)
{
if (node)
{ printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
return;
}
/* inorder tree traversal */
void inOrder(struct tnode *node)
{
if (node)
{ inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
return;
}
int main()
{
int data, ch;
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 ur 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("U've entered wrong opetion\n");
break;
}
}
return 0;
}

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy