层次遍历二叉树
2016-04-28 14:45
323 查看
采用指针的方式实现二叉树的层次遍历
#include <iostream> #include<stdlib.h> #include<stdio.h> #include<vector> using namespace std; struct TreeNode { int key; TreeNode* left; TreeNode* right; }; void PrintNodeByLevel(TreeNode* root) { if(root==NULL) return; vector<TreeNode*>vec; vec.push_back(root); int cur=0; int last=1; while(cur<vec.size()) { last=vec.size(); while(cur<last) { cout<<vec[cur]; if(vec[cur]->left) vec.push_back(vec[cur]->left); if(vec[cur]->right) vec.push_back(vec[cur]->right); cur++; } cout<<endl; } }
用队列实现
<pre name="code" class="cpp">vector<int> PrintFromTopToBottom(TreeNode *root) { queue<TreeNode*>q; vector<int>r; q.push(root); while(!root) { q.front(); q.pop(); r.push_back(root->val); q.push(root->left); q.push(root->right); } return r; }
相关文章推荐
- readlink函数:获取程序的运行路径
- UItableViewCell 重用导致控件多次加载 去除cell重用导致 视图控件多次加载问题
- Dr.Elephant开发者指南 - 【Dr.Elephant系列文章-3】
- 跨平台AR增强现实开发(三)(ARCamera功能与简介)
- IOS开发源码阅读篇--FMDB源码分析2(FMDatabase+FMDatabaseAdditions)
- POJ 3253 Fence Repair 优先队列
- POJ 3253 Fence Repair 优先队列
- 关于manacher算法求字符串中最长字符串和其长度
- ELA_Device_Lib
- 学习感悟
- git 错误 fatal: Not a valid object name: 'master'.
- 053(五十二)
- 事件对象event 和ev
- VB.net2008实例 编写文字加解密程序
- IOS开发源码阅读篇--FMDB源码分析1(FMResultSet)
- Examples of Bumblebee2 Calibration File
- android shape的使用
- 深入浅出UML类图
- 软件版本号规范
- dismissViewControllerAnimated 退两层controller