-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary_tree_stack.c
132 lines (132 loc) · 1.87 KB
/
binary_tree_stack.c
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node* lc;
struct node* rc;
}node;
int top1=-1, c[100], n=100, top2=-1;
node *b[100];
node *root,*t1,*t2;
node *create_tree(){
int d;
node *t3;
scanf("%d",&d);
while(d!=-9999){
t3=(node*)malloc(sizeof(node));
t3->data=d;
t3->lc=t3->rc=NULL;
if (root==NULL){
root=t3;
}
else{
t2=NULL;
t1=root;
while(t1!=NULL){
if (t1->data>=d){
t2=t1;
t1=t1->lc;
}
else{
t2=t1;
t1=t1->rc;
}
}
if (t2->data>=d)
t2->lc=t3;
else
t2->rc=t3;
}
scanf("%d",&d);
}
return t3;
}
void preorder(){
t1=root;
node *temp=NULL;
while(!((t1==NULL)&&(temp==NULL))){
printf("%d", t1->data);
pushpre(t1);
t1=t1->lc;
while(t1==NULL){
temp=poppre();
if(temp==NULL)
break;
t1=temp->rc;
}
}
}
void pushpre(){
if (top1>=n-1)
printf("Stack is Full\n");
else
b[++top1]=a;
}
void poppre(){
if(top1==-1)
return NULL;
else
return b[top1--];
}
void inorder(){
t1=root;
node *temp=NULL;
while(!((t1==NULL)&&(temp==NULL))){
push(t1);
t1=t1->lc;
while(t1==NULL){
temp=pop();
if(temp==NULL)
break;
printf("%d",temp->data);
t1=temp->rc;
}
}
}
void pushin(int a){
if(top2>n-1)
printf("Stack is Full\n");
else
c[++top2]=a;
}
void popin(){
if(top1==-1)
return 0;
else
return c[top1--];
}
void postorder(node *temp){
t1=root;
temp=NULL;
int temp1=0;
while(!((t1==NULL)&&(temp==NULL))){
while(t1!=NULL){
pushpre(t1);
pushin(1);
t1=t1->lc;
}
while(t1==NULL){
temp1=popin();
temp=popin();
if(temp==NULL)
break;
if(temp==1){
pushin(2);
pushpre(temp);
t1=temp->rc;
}
else
printf("%d",temp->data);
}
}
}
void main(){
node *r;
r=create_tree();
printf("\npreorder: ");
preorder(root);
printf("\ninorder: ");
inorder(root);
printf("\npostorder: ");
postorder(root);
}