-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path先序和中序构造二叉树
84 lines (84 loc) · 1.67 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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node
{
char value;
struct Node *left;
struct Node *right;
};
struct Node* createTree(char a[],char b[],int n)
{
int i=0;
struct Node *p=NULL;
p=(struct Node*)malloc(sizeof(struct Node));
if(NULL==p)
{
perror("faileed");
exit(-1);
}
p->left=NULL;
p->right=NULL;
if(0==n)
{
printf("%c",b[n]);
p->value=b[n];
return p;
}
while(b[i]!=a[0]) i++;
p->value=b[i];//子树根节点
if(i>0)
p->left=createTree(a+1,b,i-1);
if(i<n)
p->right=createTree(a+i+1,b+i+1,n-i-1);
printf("%c",b[i]);
return p;
}
void preOrder(struct Node *p)
{
if(NULL==p)
return;
printf("%c",p->value);
preOrder(p->left);
preOrder(p->right);
}
void midOrder(struct Node *p)
{
if(NULL==p)
return;
midOrder(p->left);
printf("%c",p->value);
midOrder(p->right);
}
void backOrder(struct Node *p)
{
if(NULL==p)
return;
backOrder(p->left);
backOrder(p->right);
printf("%c",p->value);
}
int main()
{
char a[100],b[100];
int alen,blen;
struct Node *root;
while(scanf("%s%s",a,b)!=EOF)
{
alen=strlen(a);//先序
blen=strlen(b);//中序
root=createTree(a,b,alen-1);
printf("\n");
printf("preOder:");
preOrder(root);
printf("\n");
printf("midOder:");
midOrder(root);
printf("\n");
printf("backOder:");
backOrder(root);
printf("\n");
}
system("pause");
return 0;
}