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

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

2012-09-13 19:46 429 查看
给定一颗二叉树,要求按分层遍历该二叉树,即从上到下按层次访问该二叉树(每一层将单独输出一行),每一行要求访问的顺序是从左到右。

《编程之美》中有递归和非递归的解法。

递归解法的思路是,假设要求访问二叉树中第K层的节点,那么可以把它转换成访问以该二叉树根节点的左右节点为根的两颗左右子树的第K-1层的节点。依次递归

下面程序是输出第K层的节点

int PrintNodeAtLevel(node *root,int level)
{
if(root==NULL|| level<0)
return 0;
if(level==0)
 {
cout << root->data << " ";
return 1;
}
return PrintNodeAtLevel(root->left,level-1)+PrintNodeAtLevel(root->right,level-1);

}
对于非递归的解法,《编程之美》上使用了一个Vector数组,然后用了两个游标来标记一层是否结束。

我自己的解法是用了两个队列。一个队列放节点,一个队列放对应的节点的层次。如果不需要每一层次输完换行的话,一个队列就够了。

#include <iostream>
#include <queue>
using namespace std;
struct node
{
node *left;
node *right;
char value;
node (char v,node *l=NULL,node *r=NULL): value(v),left(l),right(r){}
};
void PrintByLevel(node *root)
{
queue<node *> q;
queue<int> q2; //记录当前节点的层次
q.push(root);
node *p;
q2.push(0);
while(!q.empty())
{
p=q.front();
if(p->left)
{
q.push(p->left);
q2.push(q2.front()+1);
}
if(p->right)
{
q.push(p->right);
q2.push(q2.front()+1);
}
cout << p->value;
q.pop();
int temp=q2.front();
q2.pop();
if(q2.empty() ||temp!=q2.front())
cout << endl;
}
}
int main()
{
node *h=new node('h');
node *i=new node('i');
node *e=new node('e',h);
node *c=new node('c',e);
node *f=new node('f',NULL,i);
node *g=new node('g');
node *d=new node('d',f,g);
node *b=new node('b',c,d);
node *a=new node('a',NULL,b);

PrintByLevel(a);

}


扩展问题:

1. 如果要求按深度从下到上访问二叉树,每层的访问顺序仍然是从左到右,如何改进?

可以在《编程之美》的基础上改,用vector,和两个游标。。。
void PrintByReverseLevel(node *root)
{
vector<node *> q;
stack<int> q2; //记录当前节点的层次
node *p;
q.push_back(root);
q2.push(0);
int cur=0;
int last=1;
while(cur<q.size())
{
int level=q2.top();
last=q.size();
while(cur<last)
{
p=q[cur];
if(p->right)
{
q.push_back(p->right);
q2.push(level+1);
}
if(p->left)
{
q.push_back(p->left);
q2.push(level+1);
}
cur++;
}
}
while(!q2.empty())
{
cout << q[--cur]->value;
int temp=q2.top();
q2.pop();
if(q2.empty() || temp!=q2.top())
cout << endl;
}
}


2. 如果按深度从下到上访问,每层的访问顺序变成从右到左,算法又该怎么改进?

对上个程序做下修改,改变左右节点进vector的顺序即可
void PrintByReverseLevel2(node *root)
{
vector<node *> q;
stack<int> q2; //记录当前节点的层次
node *p;
q.push_back(root);
q2.push(0);
int cur=0;
int last=1;
while(cur<q.size())
{
int level=q2.top();
last=q.size();
while(cur<last)
{
p=q[cur];
if(p->left)
{
q.push_back(p->left);
q2.push(level+1);
}
if(p->right)
{
q.push_back(p->right);
q2.push(level+1);
}
cur++;
}
}
while(!q2.empty())
{
cout << q[--cur]->value;
int temp=q2.top();
q2.pop();
if(q2.empty() || temp!=q2.top())
cout << endl;
}
}
本文转自:http://blog.csdn.net/kindlucy/article/details/5587231
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息