-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree Traversals.cpp
More file actions
executable file
·80 lines (77 loc) · 1.51 KB
/
Copy pathTree Traversals.cpp
File metadata and controls
executable file
·80 lines (77 loc) · 1.51 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
class BinaryTree {
public:
BinaryTree(int val) : val(val) {
parent = nullptr;
left = nullptr;
right = nullptr;
}
~BinaryTree() {
if (left != nullptr) {
delete left;
}
if (right != nullptr) {
delete right;
}
}
friend ostream &operator<<(ostream &os, BinaryTree const *bt) {
if (bt->left != nullptr) {
os << bt->left;
}
if (bt->right != nullptr) {
os << bt->right;
}
os << bt->val << " ";
return os;
}
BinaryTree *parent;
BinaryTree *left;
BinaryTree *right;
int val;
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<int> preorder(n);
vector<int> inorder(n);
vector<int> postorder(n);
for (auto &x : preorder) cin >> x;
for (auto &x : inorder) cin >> x;
vector<bool> odw(n + 1);
int i = 1, j = 0;
BinaryTree *root = new BinaryTree(preorder[0]);
BinaryTree *act = root;
odw[preorder[0]] = true;
for (; i < n;) {
if (odw[inorder[j]] == true) {
if (odw[inorder[j + 1]] == true) {
int val = act->val;
act = act->parent;
if (act->right != nullptr && act->right->val == val) {
j--;
}
} else {
act->right = new BinaryTree(preorder[i]);
act->right->parent = act;
odw[preorder[i]] = true;
i++;
act = act->right;
}
j++;
} else {
act->left = new BinaryTree(preorder[i]);
act->left->parent = act;
odw[preorder[i]] = true;
i++;
act = act->left;
}
}
cout << root << "\n";
delete root;
return 0;
}