AcWing 44. 分行从上往下打印二叉树
原题链接
中等
作者:
Value
,
2020-09-15 10:53:57
,
所有人可见
,
阅读 554
/**
* 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:
struct node{
TreeNode * p;
int step;
};
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<node> qu;
qu.push({root, 0});
int cur = 0;
vector<int> tmp;
while(!qu.empty()){
node now = qu.front();
qu.pop();
if(now.step == cur) tmp.push_back({now.p->val});
else{
if(tmp.size() != 0) res.push_back(tmp);
tmp.clear();
cur = now.step;
tmp.push_back(now.p->val);
}
if(now.p->left) qu.push({now.p->left, now.step + 1});
if(now.p->right) qu.push({now.p->right, now.step + 1});
}
if(tmp.size() != 0) res.push_back(tmp);
return res;
}
};
1