题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
if(root==NULL) return {};
vector<int> res; //存储结果
queue<TreeNode*> que; //队列实现BFS
que.push(root);
while(que.size()!=0){
res.push_back(que.front()->val); //队头值进入res
if(que.front()->left!=NULL) que.push(que.front()->left); //左右不空就进入队列
if(que.front()->right!=NULL) que.push(que.front()->right);
que.pop(); //当前队头出队
}
return res;
}
};