题目链接:https://www.acwing.com/problem/content/41/
题目如下:
/**
* 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> result;
if(root==NULL) return result;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
int size=que.size();//每一层要遍历的数量
while(size--){//注意:要先执行再减一,不能先减一再执行
TreeNode* temp=que.front();
que.pop();
result.push_back(temp->val);
if(temp->left) que.push(temp->left);
if(temp->right) que.push(temp->right);
}
}
return result;
}
};