-
Notifications
You must be signed in to change notification settings - Fork 6
/
06_ConstructBinaryTree.cpp
111 lines (93 loc) · 1.96 KB
/
06_ConstructBinaryTree.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
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
struct BinaryTreeNode
{
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
BinaryTreeNode(int val) {
value = val;
left = NULL;
right = NULL;
}
};
BinaryTreeNode* ConstructTree(vector<int>::const_iterator prebeg,
vector<int>::const_iterator preend,
vector<int>::const_iterator inbeg,
vector<int>::const_iterator inend)
{
BinaryTreeNode *root = new BinaryTreeNode(*prebeg);
if (prebeg == preend)
{
if (inbeg == inend && *inbeg == *prebeg)
return root;
else
throw runtime_error("Invalid input.");
}
vector<int>::const_iterator index;
index = inbeg;
while(*index != root->value && index != inend)
index ++;
if (index == inend && *index != root->value)
throw runtime_error("Invalid input.");
int leftlength = index - inbeg;
if (leftlength > 0)
{
root->left = ConstructTree(prebeg + 1, prebeg + leftlength, inbeg, index - 1);
}
if (inend > index)
{
root->right = ConstructTree(prebeg + leftlength + 1, preend, index + 1, inend);
}
return root;
}
int AfterOrder(BinaryTreeNode *root)
{
if (root == NULL)
return 0;
if (root->left)
AfterOrder(root->left);
if (root->right)
AfterOrder(root->right);
cout << root->value << " ";
return 0;
}
int main(void)
{
int n, i = 0;
while (cin >> n)
{
vector<int> preorder(n);
vector<int> inorder(n);
i = 0;
while (i < n)
{
cin >> preorder[i];
i ++;
}
i = 0;
while (i < n)
{
cin >> inorder[i];
i ++;
}
if (n == 0)
{
cout << "No" << endl;
continue;
}
BinaryTreeNode *root;
vector<int>::const_iterator prebeg = preorder.begin();
vector<int>::const_iterator preend = preorder.end();
vector<int>::const_iterator inbeg = inorder.begin();
vector<int>::const_iterator inend = inorder.end();
root = ConstructTree(prebeg, preend-1, inbeg, inend-1);
if (root == NULL)
continue;
AfterOrder(root);
cout << endl;
}
return 0;
}