从上往下打印出二叉树(二十二)

题目描述:

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

代码(已在牛客上 AC)

BST.

class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
if (!root) return {};
vector<int> res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
auto root = q.front();
q.pop();
res.push_back(root->val);
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
return res;
}
};