-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathleetcode103-zigzag-traverse_queue.cpp
73 lines (65 loc) · 1.97 KB
/
leetcode103-zigzag-traverse_queue.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
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if (!root) return {};
if (root->left == nullptr && root->right == nullptr) return {{root->val}};
vector<vector<int>> res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
vector<int> curLevel;
for (int i = q.size() ; i > 0; --i)
{
TreeNode* p = q.front();
q.pop();
curLevel.push_back(p->val);
if (p->left != nullptr) q.push(p->left); /* 不能写出 !p->left 或 !(p->left) */
if (p->right != nullptr) q.push(p->right);
}
res.push_back(curLevel);
}
for (int i = 0; i < res.size(); i++)
{
vector<int> curLevel = res[i];
if (i % 2 == 1)
{
reverse(curLevel.begin(), curLevel.end());
res[i] = curLevel;
}
}
return res;
}
};
// Test
int main()
{
Solution sol;
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
root->right->left = new TreeNode(15);
root->right->left->left = nullptr;
root->right->left->right = nullptr;
root->right->right = new TreeNode(7);
root->right->right->left = nullptr;
root->right->right->right = nullptr;
vector<vector<int>> res = sol.zigzagLevelOrder(root);
return 0;
}