Skip to content

Commit 8b6208c

Browse files
authored
up 103. 二叉树的锯齿形层序遍历
1 parent 79efcb4 commit 8b6208c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

algorithms/algo_notes/二叉树合集.md

+49
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,52 @@ public:
2323
}
2424
};
2525
```
26+
27+
## 103 按Z字形打印二叉�树 https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
28+
29+
思路:用一个队列,一个bool标志位实现,每次遍历完取队列头元素之后反转
30+
31+
```c++
32+
/*
33+
struct TreeNode {
34+
int val;
35+
struct TreeNode *left;
36+
struct TreeNode *right;
37+
TreeNode(int x) :
38+
val(x), left(NULL), right(NULL) {
39+
}
40+
};
41+
*/
42+
43+
class Solution {
44+
public:
45+
std::vector<vector<int> > Print(TreeNode* pRoot) {
46+
std::vector<vector<int>> res;
47+
if (!pRoot) return res;
48+
std::queue<TreeNode*>q;
49+
q.push(pRoot);
50+
bool even = false;
51+
while(!q.empty()) {
52+
std::vector<int>vec;
53+
const int size = q.size();
54+
for(int i = 0; i < size; ++i) {
55+
TreeNode* node = q.front();
56+
q.pop();
57+
vec.push_back(node->val);
58+
if (node->left) {
59+
q.push(node->left);
60+
}
61+
if (node->right) {
62+
q.push(node->right);
63+
}
64+
}
65+
if (even) {
66+
std::reverse(vec.begin(), vec.end());
67+
}
68+
res.push_back(vec);
69+
even = !even;
70+
}
71+
return res;
72+
}
73+
};
74+
```

0 commit comments

Comments
 (0)