想法
在二叉树不分行从上往下打印二叉树的基础上,做一个微小的改动。
为队列中的每个节点指针附加上一个层次信息。
代码实现
/**
* 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<pair<TreeNode*, int>> q;
q.push({root, 0});
while (q.size())
{
auto t = q.front();
q.pop();
if (res.size() < t.second + 1) res.push_back({t.first->val});
else res[t.second].push_back({t.first->val});
if (t.first->left) q.push({t.first->left, t.second + 1});
if (t.first->right) q.push({t.first->right, t.second + 1});
}
return res;
}
};