AcWing 43. 不分行从上往下打印二叉树
原题链接
简单
作者:
我要出去乱说
,
2021-02-08 21:40:54
,
所有人可见
,
阅读 440
/**
* 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<int> printFromTopToBottom(TreeNode* root) {
vector<int> res;
if (!root) return res; //判空
queue<TreeNode*> q; //宽搜需要队列
q.push(root);
while (q.size())
{
auto t = q.front();
q.pop();
res.push_back(t->val); //先将当前节点的值放入vector
if (t->left) q.push(t->left); //再分别push当前节点的左右子节点
if (t->right) q.push(t->right);
}
return res;
}
};