-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreoder_to_bst.c
90 lines (85 loc) · 1.53 KB
/
preoder_to_bst.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
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *lchild;
int data;
struct node *rchild;
}*root=NULL;
typedef struct stack
{
struct node* a[20];
int top;
}stack;
void push(stack *st,struct node *x)
{
st->a[++st->top]=x;
}
struct node* pop(stack *st)
{
struct node* x;
x=st->a[st->top--];
return x;
}
int stacktop(stack *st)
{
struct node *m;
if(st->top)
{
m= st->a[st->top];
return m->data;
}
else
return 4936854;
}
void inorder(struct node* p)
{
if(p)
{
inorder(p->lchild);
printf("%d ",p->data);
inorder(p->rchild);
}
}
void create(int *a,int n)
{ stack st;
st.top==-1;
int i=0;
struct node *t,*p;
root=(struct node *)malloc(sizeof(struct node));
root->data=a[i++];
root->lchild=root->rchild=NULL;
p=root;
while(i<n)
{
t=(struct node*)malloc(sizeof(struct node));
if(a[i]<p->data)
{
t->data=a[i++];
t->rchild=t->lchild=NULL;
p->lchild=t;
push(&st,p);
p=t;
}
else
{
if(a[i]>p->data&&a[i]<stacktop(&st))
{
t->data=a[i++];
t->rchild=t->lchild=NULL;
p->rchild=t;
p=t;
}
else
{
p=pop(&st);
}
}
}
inorder(root);
}
void main()
{
int a[8]={30,20,10,15,25,40,50,45};
create(a,8);
}