forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarytree.c
More file actions
89 lines (88 loc) · 1.32 KB
/
binarytree.c
File metadata and controls
89 lines (88 loc) · 1.32 KB
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
/*Iterative Tree Traversals*/
#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
#include "Stack.h"
struct Node *root=NULL;
void Treecreate()
{
struct Node *p,*t;
int x;
struct Queue q;
create(&q,100);
printf("Eneter root value ");
scanf("%d",&x);
root=(struct Node *)malloc(sizeof(struct Node));
root->data=x;
root->lchild=root->rchild=NULL;
enqueue(&q,root);
while(!isEmpty(q))
{
p=dequeue(&q);
printf("eneter left child of %d ",p->data);
scanf("%d",&x);
if(x!=-1)
{
t=(struct Node *)malloc(sizeof(struct Node));
t->data=x;
t->lchild=t->rchild=NULL;
p->lchild=t;
enqueue(&q,t);
}
printf("eneter right child of %d ",p->data);
scanf("%d",&x);
if(x!=-1)
{
t=(struct Node *)malloc(sizeof(struct Node));
t->data=x;
t->lchild=t->rchild=NULL;
p->rchild=t;
enqueue(&q,t);
}
}
}
void IPreorder(struct Node *p)
{
struct Stack stk;
Stackcreate(&stk,100);
while(p || !isEmptyStack(stk))
{
if(p)
{
printf("%d ",p->data);
push(&stk,p);
p=p->lchild;
}
else
{
p=pop(&stk);
p=p->rchild;
}
}
}
void IInorder(struct Node *p)
{
struct Stack stk;
Stackcreate(&stk,100);
while(p || !isEmptyStack(stk))
{
if(p)
{
push(&stk,p);
p=p->lchild;
}
else
{
p=pop(&stk);
printf("%d ",p->data);
p=p->rchild;
}
}
}
int main()
{
Treecreate();
IPreOrder(root);
IInorder(root);
return 0;
}