AcWing 45. 【45. 之字形打印二叉树】简洁酷炫
原题链接
简单
作者:
mui
,
2020-04-05 02:59:02
,
所有人可见
,
阅读 543
/**
* 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) {
vector<vector<int>> res {};
if (!root) return res;
queue<TreeNode*> q ({root});
int level = 0;
for (; !q.empty(); ++level)
{
int size = q.size();
vector<int> row {};
for (int i = 0; i < size; ++i)
{
TreeNode *node = q.front(); q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
row.push_back(node->val);
}
if (level % 2 != 0) res.emplace_back(vector<int> {row.rbegin(), row.rend()});
else res.emplace_back(row);
}
return res;
}
};