您的位置:首页 > 其它

层次遍历二叉树

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;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: