-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP536.cpp
62 lines (55 loc) · 1.29 KB
/
P536.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
#include <iostream>
#include <stdio.h>
struct Node {
Node *l, *r;
char c;
};
void buildTree(Node *tree, int &numNodes, char *preorder, char *inorder, int len) {
char root = preorder[0];
int nodeIdx = numNodes;
tree[nodeIdx].c = root;
++numNodes;
int lenLeft = 0;
char c;
while((c = inorder[lenLeft]) != root)
++lenLeft;
int lenRight = len - 1 - lenLeft;
// Handle left child:
if(lenLeft == 0) {
tree[nodeIdx].l = NULL;
}
else {
tree[nodeIdx].l = &tree[numNodes];
buildTree(tree, numNodes, &preorder[1], inorder, lenLeft);
}
// Handle right child:
if(lenRight == 0) {
tree[nodeIdx].r = NULL;
}
else {
tree[nodeIdx].r = &tree[numNodes];
buildTree(tree, numNodes, &preorder[1+lenLeft], &inorder[1+lenLeft], lenRight);
}
}
void writePostOrder(Node *tree) {
if(tree->l != NULL)
writePostOrder(tree->l);
if(tree->r != NULL)
writePostOrder(tree->r);
std::cout << tree->c;
}
int main() {
char c, preorder[39], inorder[39];
Node tree[39];
while(std::cin >> preorder >> inorder) {
// Reset tree:
int numNodes = 0;
int len = 0;
while((c = preorder[len]) >= 'A' && c <= 'Z')
++len;
buildTree(tree, numNodes, preorder, inorder, len);
writePostOrder(tree);
std::cout << std::endl;
}
return 0;
}