问题
按之字形层序遍历二叉树
算法:BFS
这道题容易想复杂,事实上,只需要考虑下之字形和正常层序遍历的区别即可:隔层反序
我们正常遍历每一层都会得到一个数组,那么只需要隔一层用reverse反转即可
时间复杂度
$O(N)$
代码
/**
* 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>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
vector<vector<int>> ans;
if(!root) return ans;
q.push(root);
bool zigzag = false;
while(q.size()){
int cnt = q.size();
vector<int> temp;
for(int i = 0; i < cnt; i ++){
TreeNode* u = q.front();
q.pop();
if(u->left) q.push(u->left);
if(u->right) q.push(u->right);
temp.push_back(u->val);
}
if(zigzag) reverse(temp.begin(), temp.end());
zigzag = !zigzag;
ans.push_back(temp);
}
return ans;
}
};