File tree 1 file changed +49
-0
lines changed
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -23,3 +23,52 @@ public:
23
23
}
24
24
};
25
25
```
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
+ ```
You can’t perform that action at this time.
0 commit comments