思路:巧妙利用队列先进先出的性质
/*
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;
if(root==NULL) return ans;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
TreeNode* fr = q.front();
ans.push_back(fr->val);
if(fr->left)
{
q.push(fr->left);
}
if(fr->right)
{
q.push(fr->right);
}
q.pop();
}
return ans;
}
};
京公网安备 11010502036488号