-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-zigzag-level-order-traversal.cc
79 lines (66 loc) · 1.6 KB
/
binary-tree-zigzag-level-order-traversal.cc
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
// https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
// http://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/
// http://leetcode.com/2010/09/printing-binary-tree-in-zig-zag-level_18.html
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > res;
vector<int> values;
stack<TreeNode*> currentLevel, nextLevel;
bool leftToRight = true;
currentLevel.push(root);
while (!currentLevel.empty()) {
TreeNode *node = currentLevel.top();
currentLevel.pop();
if (node != NULL) {
values.push_back(node->val);
if (leftToRight) {
nextLevel.push(node->left);
nextLevel.push(node->right);
} else {
nextLevel.push(node->right);
nextLevel.push(node->left);
}
}
if (currentLevel.empty()) {
if (!values.empty()) {
res.push_back(values);
values.clear();
}
leftToRight = !leftToRight;
swap(currentLevel, nextLevel);
}
}
return res;
}
};
int main(int argc, char const* argv[]) {
TreeNode *a1 = new TreeNode(1);
TreeNode *a2 = new TreeNode(2);
TreeNode *a3 = new TreeNode(3);
TreeNode *a4 = new TreeNode(4);
TreeNode *a5 = new TreeNode(5);
a1->left = a2;
a2->left = a4;
a1->right = a3;
a3->right = a5;
Solution s;
vector<vector<int> > v = s.zigzagLevelOrder(a1);
for (auto &vv : v) {
for (auto n : vv) {
cout << n << " ";
}
cout << endl;
}
return 0;
}