-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.tree.cpp
117 lines (106 loc) · 2.74 KB
/
5.tree.cpp
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
/*************************************************************************
> File Name: 5.tree.cpp
> Author: Mendy
> Mail: [email protected]
> Course:
> Created Time: 六 4/20 12:18:41 2019
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node{
int data;
struct Node *lchild;
struct Node *rchild;
} Node;
Node *init(int data){
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->lchild = node->rchild = NULL;
return node;
}
/*先序遍历*/
void preorder(Node *root){
printf("%d ", root->data);
if(root->lchild){
preorder(root->lchild);
}
if(root->rchild){
preorder(root->rchild);
}
}
/*中序遍历*/
void inorder(Node *root){
if(root->lchild){
inorder(root->lchild);
}
printf("%d ", root->data);
if(root->rchild){
inorder(root->rchild);
}
}
/*后序遍历*/
void postorder(Node *root){
if(root->lchild){
postorder(root->lchild);
}
if(root->rchild){
postorder(root->rchild);
}
printf("%d ", root->data);
}
/*已知先序遍历中序遍历,构造二叉树*/
Node *BuildPostorderTree(char PreOrderStr[], char InOrderStr[], int len){
Node *p = init(PreOrderStr[0] - '0');
int pos = strchr(InOrderStr, PreOrderStr[0]) - InOrderStr;
if(pos > 0){
p->lchild = BuildPostorderTree(PreOrderStr + 1, InOrderStr, pos);
}
if(pos + 1 < len){
p->rchild = BuildPostorderTree(PreOrderStr + pos + 1, InOrderStr + pos + 1, len - pos - 1);
}
return p;
}
/*已知中序遍历后序遍历,构造二叉树*/
Node *BuildPreorderTree(char PostOrderStr[], char InOrderStr[], int len){
Node *p = init(PostOrderStr[len - 1] - '0');
int pos = strchr(InOrderStr, PostOrderStr[len - 1]) - InOrderStr;
if(pos > 0){
p->lchild = BuildPreorderTree(PostOrderStr, InOrderStr, pos);
}
if(pos + 1 < len){
p->rchild = BuildPreorderTree(PostOrderStr + pos, InOrderStr + pos + 1, len - pos - 1);
}
return p;
}
void clear(Node *node){
if(node->lchild){
clear(node->lchild);
}
if(node->rchild){
clear(node->rchild);
}
free(node);
}
int main(){
Node *node = init(1);
node->lchild = init(2);
node->rchild = init(3);
preorder(node);
printf("\n");
inorder(node);
printf("\n");
postorder(node);
printf("\n");
clear(node);
char pre[] = "136945827";
char in[] = "963548127";
char post[] = "965843721";
node = BuildPostorderTree(pre, in, strlen(pre));
postorder(node);
printf("\n");
node = BuildPreorderTree(post, in, strlen(post));
preorder(node);
printf("\n");
return 0;
}