链接
https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
耗时
解题:14 min
题解:8 min
题意
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
思路
BFS 对树进行层次遍历,与常规方法的区别在于锯齿形。设置一个 flag,flag 为 false 正放,true 反放。
时间复杂度: O ( n o d e ) O(node) O(node)
AC代码
/**
* 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) {
queue<TreeNode*> q;
if(root != NULL) q.push(root);
vector<vector<int>> ans;
bool flag = false;
while(!q.empty()) {
int n = q.size();
vector<int> tmp;
for(int i = 0; i < n; ++i) {
TreeNode* now = q.front();
q.pop();
tmp.push_back(now->val);
if(now->left != NULL) q.push(now->left);
if(now->right != NULL) q.push(now->right);
}
if(flag) {
reverse(tmp.begin(), tmp.end());
}
flag = !flag;
ans.push_back(tmp);
}
return ans;
}
};