Pes2ug20cs282 - Rohit V Shastry - Sec E - Week 8
Pes2ug20cs282 - Rohit V Shastry - Sec E - Week 8
Pes2ug20cs282 - Rohit V Shastry - Sec E - Week 8
code
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
struct node* newNode(int item)
{
struct node* temp
= (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
struct node* insert(struct node* node, int key)
{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
return node;
}
struct node* minValueNode(struct node* node)
{
struct node* current = node;
root->key = temp->key;
OUTPUT:
Program 2a
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<malloc.h>
struct node {
struct node *right,*left,*prev;
char data;
}*cur,*par,*root=NULL;
void preorder(struct node *);
void postorder(struct node *);
void inorder(struct node *);
int eval(struct node* root)
{
if (!root)
return 0;
int l_val = eval(root
->left);
if ((root
->data)=='+')
return l_val+r_val;
if (root
->data=='
-')
return l_val
-r_val;
if (root
->data=='*')
return l_val*r_val;
return l_val/r_val;
}
int main()
{
char a[100];
int len,i;
struct node *new_node;
printf("Enter Postfix Expression\n");
gets(a);
len=strlen(a);
for(i=len-1 ; i>=0 ; i--)
{
new_node=(struct node *)malloc(sizeof(struct node));
new_node->data=a[i];
new_node->left=new_node->right=new_node->prev=NULL;
if(root==NULL)
{
root=new_node;
cur=par=root;
}
else
{
if(a[i]=='+' ||a[i]=='-' ||a[i]=='*'||a[i]=='/')
{
if(par->right==NULL)
{
cur=new_node;
par->right=cur;
cur->prev=par;
par=cur;
}
else if(par->left==NULL)
{
cur=new_node;
par->left=cur;
cur->prev=par;
par=cur;
}
else
{
while(par
->left!=NULL)
{
par=par
->prev;
}
cur=new_node;
par
->left=cur;
cur
->prev=par;
par=cur;
}
}
else
{
if(par
->right==NULL)
{
cur=new_node;
par
->right=cur;
cur
->prev=par;
}
else if(par
->left==NULL)
{
cur=new_node;
par
->left=cur;
cur
->prev=par;
}
else
{
while(par
->left!=NULL)
{
par=par
->prev;
}
cur=new_node;
par
->left=cur;
cur
->prev=par;
}}
printf("
\nInorder Traversal:
\n");
inorder(root);
printf("
\
n
\nPreorder Traversal:
\n");
preorder(root);
printf("
\
n
\nPostorder Traversal:
\n");
postorder(root);
printf("
\n value is :
-10");
eval(root);
return 0;
getch(); }
void inorder(struct node *root) {
if(root!=NULL) {
inorder(root
->left);
printf("%c
\t",root
->data);
inorder(root
->right);
}}
void preorder(struct node *root) {
if(root!=NULL) {
printf("%c
\t",root
->data);
preorder(root
->left);
preorder(root
->right);
}}
void postorder(struct node *root) {
if(root!=NULL) {
postorder(root->left);
postorder(root->right);
printf("%c\t",root->data);
}
}
Output: