C++版 - 剑指offer 面试题23:从上往下打印二叉树(二叉树的层次遍历BFS) 题解
2024-10-11 09:40:45
剑指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;
}
最新文章
- 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) 收藏
- orale 函数大全[转]
- 近期C#项目中总结
- document.forms[0].submit object is not a function
- linux (centos) 单机50w+链接 内核参数配置
- 认识C和内存管理
- Leetcode: Elimination Game
- Dynamic view
- c++ 钻石继承
- JPA project Change Event Handler问题解决[转]
- 安卓模拟器";bluestacks";在电脑上的设置.(宽,高)
- WampServer2.5的XDebug调试不成功的原因
- unity3d银联支付出现闪退
- Quercus
- :nth-child(n)
- Splinter常用API介绍(转)
- slider插件制作轮播图
- 8 -- 深入使用Spring -- 5... Spring 3.1 新增的缓存机制
- hibernate文档头的不同版本
- JSz中的静态方法和实例方法的分析