AcWing 45. 之字形打印二叉树
原题链接
中等
C++ 代码(简单易懂)
// 二叉树层序遍历的变形(null标记)
/**
* 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>> printFromTopToBottom(TreeNode* root) {
if(!root) return vector<vector<int>>();
vector<vector<int>> res;
vector<int> temp;
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
int curnum = 0; // 统计当前二叉树的层数
while(q.size())
{
auto cur = q.front();
q.pop();
if(cur)
{
temp.push_back(cur->val);
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
else
{
curnum++;
if(curnum % 2 == 1) res.push_back(temp);
else res.push_back(vector<int>(temp.rbegin(), temp.rend()));
temp.clear();
if(q.size()) // 当前的null不是最后一个null继续加入,否则就不再加入null了。
q.push(nullptr);
}
}
return res;
}
};