您的位置:首页 > 编程语言

编程之美3.10 分层遍历二叉树

2013-08-23 23:06 316 查看
推荐http://blog.csdn.net/ididcan/article/details/7985741

这个对扩展问题弄的比较好,但是可以考虑用栈来实现http://blog.csdn.net/houhouzhe/article/details/6546950

两个问题

1、分层遍历二叉树

2、打印某个层次中的节点(其中根节点是0层)

#include <iostream>
#include<vector>
using namespace std;
struct Node{
int data;
Node* left;
Node* right;
};
//max{d(u1,v1),...d(uk,vk),max1+max2+2}
void build(Node *&root){
Node *t1 = new Node();
t1->data = 1;
Node *t2 = new Node();
t2->data = 2;
Node *t3 = new Node();
t3->data = 3;
Node *t4 = new Node();
t4->data = 4;
Node *t5 = new Node();
t5->data = 5;
Node *t6 = new Node();
t6->data = 6;
Node *t7 = new Node();
t7->data = 7;
Node *t8 = new Node();
t8->data = 8;
Node *t9 = new Node();
t9->data = 9;
t1->left = t2;
t1->right = t3;
t2->left = t4;
t2->right = t5;
t4->left = t6;
t4->right = t7;
t6->left = t8;
t6->right = NULL;
t7->left = NULL;
t7->right = t9;
t3->left = NULL;
t3->right = NULL;
t5->left = NULL;
t5->right = NULL;
t8->left = NULL;
t8->right = NULL;
t9->left = NULL;
t9->right = NULL;
root = t1;
}
void prints(Node *root){
if(root==NULL)return;
if(root->left)prints(root->left);
if(root->right)prints(root->right);
cout<<root->data<<"  ";
}
int max(int a,int b){
return a>b?a:b;
}
void PrintNodeAtLevel1(Node *root,int level){
if(level==0){
if(root!=NULL){
cout<<root->data<<"  ";
return;
}
else
return;
}
if(root==NULL)return;
PrintNodeAtLevel1(root->left,level-1);
PrintNodeAtLevel1(root->right,level-1);
}
int PrintNodeAtLevel(Node *root,int level){//书上的代码
if(!root||level<0){
return 0;
}
if(level==0){
cout<<root->data<<" ";
return 1;
}
return PrintNodeAtLevel(root->left,level-1)+PrintNodeAtLevel(root->right,level-1);
}
void Printall(Node *root){
for(int i=0;i<5;i++){
PrintNodeAtLevel(root,i);
cout<<endl;
}
}
void PrintNodeByLevel(Node *root){
if(root==NULL)return;
vector<Node*> vec;
vec.push_back(root);
int cur = 0;
int last = 1;
while(cur<vec.size()){
last = vec.size();
while(cur<last){
cout<<vec[cur]->data<<" ";
if(vec[cur]->left){
vec.push_back(vec[cur]->left);
}
if(vec[cur]->right){
vec.push_back(vec[cur]->right);
}
cur++;
}
}
}
int main(){
Node *root;
build(root);
prints(root);
cout<<endl;
//cout<<PrintNodeAtLevel(root,1);
//Printall(root);
PrintNodeByLevel(root);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程之美