103 二叉树的锯齿形层序遍历

本文最后更新于:2021年1月24日 下午

给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

返回锯齿形层序遍历如下:

1
2
3
4
5
[
[3],
[20,9],
[15,7]
]

Solution

方法同 [102 二叉树的层序遍历]

  • 利用队列
  • 自顶向下的层序遍历过程中,隔层反转当层节点顺序
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
// @lc code=start
/**
* 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:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;

queue<TreeNode *> q;
q.push(root);
bool flag = 0; // 1-奇数层 0-偶数层
while(!q.empty()){
flag = !flag;
int n = q.size();
vector<int> level;
for(int i=0; i<n; ++i){
TreeNode* node = q.front();
q.pop();
level.push_back(node->val);
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
if(!flag)
reverse(level.begin(), level.end());
res.push_back(level);
}
return res;
}
};
// @lc code=end

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!