剑指offer  面试题23:从上往下打印二叉树

参与人数:4853  时间限制:1秒  空间限制:32768K

提交网址: http://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

分析:

此题即为二叉树的BFS,使用队列可以解决。

AC代码:

#include<cstdio>
#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(0);
if(root==NULL) return res; queue<TreeNode*> q;
q.push(root); while(!q.empty())
{
TreeNode *p= q.front();
res.push_back(p->val);
q.pop();
if(p->left != NULL) q.push(p->left);
if(p->right != NULL) q.push(p->right);
}
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)
printf("%d ",i); // 此处为vector遍历的方法,C++11标准支持
return 0;
}

最新文章

  1. walk around by The provided App differs from another App with the same version and product ID 分类: Sharepoint 2015-07-05 08:14 4人阅读 评论(0) 收藏
  2. orale 函数大全[转]
  3. 近期C#项目中总结
  4. document.forms[0].submit object is not a function
  5. linux (centos) 单机50w+链接 内核参数配置
  6. 认识C和内存管理
  7. Leetcode: Elimination Game
  8. Dynamic view
  9. c++ 钻石继承
  10. JPA project Change Event Handler问题解决[转]
  11. 安卓模拟器&quot;bluestacks&quot;在电脑上的设置.(宽,高)
  12. WampServer2.5的XDebug调试不成功的原因
  13. unity3d银联支付出现闪退
  14. Quercus
  15. :nth-child(n)
  16. Splinter常用API介绍(转)
  17. slider插件制作轮播图
  18. 8 -- 深入使用Spring -- 5... Spring 3.1 新增的缓存机制
  19. hibernate文档头的不同版本
  20. JSz中的静态方法和实例方法的分析

热门文章

  1. java笔记:排错5:误删maven target:恢复不了,怎么再生成
  2. 2018-2019网络对抗技术 20165220 Exp4 恶意代码分析
  3. quartz之CronExpression表达式
  4. altiumdesigner的基本你操作
  5. hadoop ha zkfc 异常自动切换机制和hdfs 没有空间问题解决
  6. 操作系统PV编程题目总结一
  7. jQuery各类选择器
  8. 两种方法上传本地文件到github(转)
  9. AT与ATX电源 - 1 系统状态
  10. md5 加密文件