-
Notifications
You must be signed in to change notification settings - Fork 0
/
103.binary-tree-zigzag-level-order-traversal.cpp
117 lines (113 loc) · 3.03 KB
/
103.binary-tree-zigzag-level-order-traversal.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
112
113
114
115
116
117
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/*
reverse function
1. level.insert(level.begin(), 1, node->val)
2. level[qs - 1 - i] = node->val
3. reverse(level.begin(), level.end())
4. vector<int>(level.rbegin(), level.level.rend())
*/
// version 1 : bfs marker NULL
/*
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) {
return res;
}
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
int tag = 0; // bool l2r !l2r
vector<int> level;
while (!q.empty()) {
TreeNode *node = q.front();
q.pop();
if (!node) {
res.push_back(level);
level.clear();
tag ++;
if (!q.empty()) {
q.push(NULL);
}
} else {
if (tag % 2) {
level.push_back(node->val);
} else {
level.insert(level.begin(), 1, node->val);
}
if (node->right) {
q.push(node->right);
}
if (node->left) {
q.push(node->left);
}
}
}
return res;
}
*/
// version 2 : bfs for loop
/*
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
if (!root) {
return res;
}
q.push(root);
int tag = 0;
while (!q.empty()) {
int qs = q.size();
vector<int> level;
for (int i = 0; i < qs; i++) {
TreeNode *node = q.front();
q.pop();
if (!(tag % 2)) {
level.push_back(node->val); // level[i] =
} else {
level.insert(level.begin(), 1, node->val); // level[qs - 1 - i] =
}
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
res.push_back(level);
tag++;
}
return res;
}
*/
// version 3 : dfs
vector<vector<int>> res;
void dfs(TreeNode* root, int depth) {
if (!root) {
return;
}
if(res.size() == depth) {
res.push_back(vector<int>());
}
if (depth % 2) {
res[depth].insert(res[depth].begin(), 1, root->val);
} else {
res[depth].push_back(root->val);
}
dfs(root->left, depth + 1);
dfs(root->right, depth + 1);
}
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
dfs(root, 0);
return res;
}
};