-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoffer-07-ConstructBinaryTree.c
More file actions
66 lines (57 loc) · 1.39 KB
/
offer-07-ConstructBinaryTree.c
File metadata and controls
66 lines (57 loc) · 1.39 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
#include <stdio.h>
#include <stdlib.h>
#include "minunit.h"
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, int inorderSize)
{
if (preorder == NULL || preorderSize == 0 || inorder == NULL || inorderSize == 0)
{
return NULL;
}
int rootIndex = 0;
for (int i = 0; i < inorderSize; i++)
{
if (inorder[i] == preorder[0])
{
rootIndex = i;
break;
}
}
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = preorder[0];
root->left = buildTree(&preorder[1], rootIndex, &inorder[0], rootIndex);
root->right = buildTree(&preorder[rootIndex + 1], preorderSize - rootIndex - 1, &inorder[rootIndex + 1], inorderSize - rootIndex - 1);
return root;
}
MU_TEST(test_case)
{
int preOrder[] = {3, 9, 20, 15, 7};
int inOrder[] = {9, 3, 15, 20, 7};
buildTree(preOrder, (int)sizeof(preOrder) / sizeof(preOrder[0]), inOrder, (int)sizeof(inOrder) / sizeof(inOrder[0]));
// todo: add print tree method
// [3,9,20,null,null,15,7]
mu_check(5 == 7);
}
MU_TEST_SUITE(test_suite)
{
MU_RUN_TEST(test_case);
}
int main()
{
MU_RUN_SUITE(test_suite);
MU_REPORT();
return MU_EXIT_CODE;
}