-
Notifications
You must be signed in to change notification settings - Fork 119
/
105.c
58 lines (44 loc) · 1.45 KB
/
105.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
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int searchNode(int inorder[], int inorderSize, int key){
int i;
for (i = 0; i < inorderSize; i++) {
if (key == inorder[i]) {
return i;
}
}
return -1;
}
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
if (preorder == NULL || inorder == NULL
|| preorderSize == 0 || inorderSize == 0) return NULL;
struct TreeNode *root
= (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = preorder[0];
int index = searchNode(inorder, inorderSize, preorder[0]);
if (index == -1) return NULL;
root->left = buildTree(preorder + 1, index, inorder, index);
root->right = buildTree(preorder + index + 1, inorderSize - index - 1,
inorder + index + 1, inorderSize - index - 1);
return root;
}
void preOrderPrint(struct TreeNode *root) {
if (root) {
printf("%d ", root->val);
preOrderPrint(root->left);
preOrderPrint(root->right);
}
}
int main() {
int pre[] = { 20, 8, 4, 12, 10, 14, 22 };
int in[] = { 4, 8, 10, 12, 14, 20, 22 };
struct TreeNode *r
= buildTree(pre, sizeof(pre)/sizeof(pre[0]), in, sizeof(in)/sizeof(in[0]));
preOrderPrint(r); printf("\n");
return 0;
}