这道题也是BFS来找的,而且这道题更简单;BFS基本思想:
这就是BFS的基本思想;不过我还是感觉如果能动态的才更好理解;
AC代码:
/**
* 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> ans;
vector<int> printFromTopToBottom(TreeNode* root) {
if(!root)return ans;
BFS(root);
return ans;
}
void BFS(TreeNode *p){
queue<TreeNode> q;//放对象进去
q.push(*p);
while(q.size()){
TreeNode *t=&q.front();//取地址出来
q.pop();
ans.push_back((t->val));
TreeNode *lt=(t->left);
TreeNode *rt=(t->right);
if(lt)q.push(*lt);//先左孩
if(rt)q.push(*rt);//再右孩
}
}
};