题解 | #从上往下打印二叉树# | C++
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> ans;
queue<TreeNode*> q;
if (root) {
q.push(root);
}
while (!q.empty()) {
int n = q.size();
while (n-- >= 1) {
ans.push_back(q.front()->val);
if (q.front()->left) q.push(q.front()->left);
if (q.front()->right) q.push(q.front()->right);
q.pop();
}
}
return ans;
}
};

