#include<iostream>
#include<vector>
#include<queue>
using namespace std;
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> res;
// 存储结果
vector<int> result;
// 边界条件
if(root == NULL)
return result;
// 辅助容器:双端队列(存储指向二叉树节点的指针)
queue<TreeNode*> q;
// 辅助指针:指向队列弹出的指针
TreeNode* fr;
// 根节点入队列
q.push(root);
// 遍历队列
while(!q.empty())
{
//
fr=q.front();
result.push_back(fr->val);
if(fr->left != NULL)
q.push(fr->left);
//cout<<fr->val;
if(fr->right != NULL)
q.push(fr->right);
//cout<<fr->val;
q.pop();
}
return result;
}
};
int main()
{
Solution sol;
vector<int> res;
TreeNode *root=new TreeNode(1);
root->right=new TreeNode(2);
root->right->left=new TreeNode(3);
root->right->left->right=new TreeNode(5);//多了这一行打印不出来,必须层层递进才能打印出二
//叉树
root->left=new TreeNode(7);
root->left->left=new TreeNode(8);
root->right->right=new TreeNode(4);//将数值填充进入后就容易观察二叉树是如何被遍历的
res=sol.PrintFromTopToBottom(root);//从左到右一层又一层的遍历,遍历后返回一个数组
//遍历的结果是1 7 2 8 3 4 5,很明显是二叉树的遍历次序
for(int i=0;i<res.size();i++){
cout<<res[i]<<endl;
}
return 0;
}