AcWing 44. 分行从上往下打印二叉树
原题链接
中等
作者:
_清醒
,
2021-05-19 17:12:06
,
所有人可见
,
阅读 300
/**
* 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;
//pair的second 用来记录层数
q.push({root,0});
//now用来记录最大层数
int now = -1;
while(q.size()){
auto t = q.front();
q.pop();
//每需要增加一层 就增加一个vector
if(t.second > now) {
res.push_back(vector<int>());
now++;
}
res[t.second].push_back(t.first->val);
//被扩展的节点 等于父节点的层数+1
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;
}
};