1 Create the binary tree with 9 nodes Figure 1 by using poin

1. Create the binary tree with 9 nodes (Figure 1) by using pointer-based representation.

struct TreeNode

{

int info;

TreeNode * left;

TreeNode * right;

}

2.

Implement pre-order, in-order, and post-order traversals, and print the results of the tree

The pre-order transversal looks like this: 2 7 2 6 5 11 5 9 4

The in-order transversal looks like this: 2 7 5 6 11 2 5 4 9

The post-order transversal looks like this: 2 5 11 6 7 4 9 5 2

Solution

Here is the code for you:

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

typedef struct node
{
int info;
struct node *left;
struct node *right;
} node;

void insert(node **,int);
void preorder(node *);
void postorder(node *);
void inorder(node *);

int main()
{
node *root;
int ch,ele;
root=NULL;
while(1)
{
printf(\"TREE OPERATIONS\ \");
printf(\"1.INSERT\ \");
printf(\"2.INORDER\ \");
printf(\"3.PREORDER\ \");
printf(\"4.POSTORDER\ \");
printf(\"5.EXIT\ \");
printf(\"Enter your choice: \");
scanf(\"%d\",&ch);
switch(ch)
{
case 1: printf(\"Enter the element you want to insert: \");
scanf(\"%d\",&ele);
insert(&root,ele);
break;
case 2: inorder(root);
break;
case 3: preorder(root);
break;
case 4: postorder(root);
break;
case 5: exit(0);
default: printf(\"Invalid Choice. Please enter a valid choice.\ \");
}
}
}

void insert(node **root, int ele)
{
node *temp,*x,*y;
x=y=*root;
temp= (node *)malloc(sizeof(node));
temp->info=ele;
temp->left = temp->right = NULL;
while(x!=NULL)
{
y=x;
if(ele < x->info)
x = x->left;
else
x = x->right;
}
if(y == NULL)
*root=temp;
else if(ele < y->info)
y->left = temp;
else
y->right = temp;
}
void inorder(node *root)
{
if(root != NULL)
{
inorder(root->left);
printf(\"%d \",root->info);
inorder(root->right);
}
}
void preorder(node *root)
{
if(root != NULL)
{
printf(\"%d \",root->info);
inorder(root->left);
inorder(root->right);
}
}
void postorder(node *root)
{
if(root != NULL)
{
inorder(root->left);
inorder(root->right);
printf(\"%d \",root->info);
}
}

1. Create the binary tree with 9 nodes (Figure 1) by using pointer-based representation. struct TreeNode { int info; TreeNode * left; TreeNode * right; } 2. Imp
1. Create the binary tree with 9 nodes (Figure 1) by using pointer-based representation. struct TreeNode { int info; TreeNode * left; TreeNode * right; } 2. Imp
1. Create the binary tree with 9 nodes (Figure 1) by using pointer-based representation. struct TreeNode { int info; TreeNode * left; TreeNode * right; } 2. Imp

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site