-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path#258.cpp
More file actions
66 lines (57 loc) · 1.35 KB
/
#258.cpp
File metadata and controls
66 lines (57 loc) · 1.35 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<deque>
#include<vector>
#include<iostream>
using namespace std;
struct Node {
int val;
Node* left;
Node* right;
Node(int v) : val{v}, left{nullptr}, right{nullptr} {}
};
vector<int> boustrophedonOrder(Node* root) {
vector<int> ret;
deque<Node*> Q{root};
bool LtoR = false;
while(!Q.empty()) {
cout << LtoR << endl;
vector<Node*> currLevel;
while(!Q.empty()) {
ret.push_back(Q.front()->val);
currLevel.push_back(Q.front());
Q.pop_front();
}
for (auto it = currLevel.rbegin(); it != currLevel.rend(); ++it) {
Node* left = (*it)->left;
Node* right = (*it)->right;
if (LtoR) {
if (left) Q.push_back(left);
if (right) Q.push_back(right);
} else {
if (right) Q.push_back(right);
if (left) Q.push_back(left);
}
}
LtoR = !LtoR;
}
return ret;
}
int main() {
Node root{1};
Node n2{2};
Node n3{3};
Node n4{4};
Node n5{5};
Node n6{6};
Node n7{7};
root.left = &n2;
root.right = &n3;
n2.left = &n4;
n2.right = &n5;
n3.left = &n6;
n3.right = &n7;
vector<int> order = boustrophedonOrder(&root);
for (int i : order) {
cout << i << " ";
}
cout << endl;
}