提交网址: http://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
分析:
此题即为二叉树的BFS,使用队列可以解决。
AC代码:
/*
从上向下打印二叉树
二叉树层次遍历
1.功能
思路:借助队列
最终返回的是vector容器
节点往容器插入一个
节点往队列 先左后右插入 再弹出
直至队列为空
2.边界 nullptr
3.错误
*/
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left,*right;
TreeNode(int x):
val(x),left(NULL),right(NULL)
{}
};
class Solution
{
public:
vector<int> PrintFromTopToBottom(TreeNode *root)
{
vector<int >res;
queue<TreeNode *> q;//辅助队列
if(root==NULL)
return res;
q.push(root);
while(!q.empty())
{
res.push_back(q.front()->val);
if(q.front()->left!=NULL)
{
q.push(q.front()->left);
}
if(q.front()->right!=NULL)
{
q.push(q.front()->right);
}
q.pop();
}
return res;
}
};
/*
以下为测试代码
*/
int main()
{
Solution sol;
vector<int> res;
TreeNode *root=new TreeNode(1);
root->right=new TreeNode(2);
root->right->left=new TreeNode(3);
res=sol.PrintFromTopToBottom(root);
for(int i:res)
cout<<i;//c++ 11标准支持 vector遍历方法
return 0;
}