作者:雨狐
题目:层次遍历输出二叉树每一层的所有结点
描述
假设二叉树中每个结点值为单个字符,采用二叉链存储结构存储。设计一个算法,采用层次遍历方法输出二叉树b中每一层的结点(每行输出一层的所有结点)。
输入
第一行:采用括号表示法的树字符串
输出
采用层次遍历方法,每行输出一层的所有结点(用空格分隔)
样例
样例输入
A(B(D,E(G,H)),C(,F(I)))
样例输出
A
B C
D E F
G H I
思路
采用循环队列按层次依次入队,通过计数每层次节点数以及头结点移动数,判断层次变化。具体实现见代码注释
代码
#include <iostream>
using namespace std;
#define MaxSize 100
typedef char ElemType;
typedef struct tnode
{ ElemType data;
struct tnode *lchild,*rchild;
} BTNode;
void CreateBTree(BTNode * &bt,char *str)//由括号表示串创建二叉链
{ BTNode *St[MaxSize],*p=NULL;
int top=-1,k,j=0;
char ch;
bt=NULL; //建立的二叉树初始时为空
ch=str[j];
while (ch!='\0') //str未扫描完时循环
{ switch(ch)
{
case '(':top++;St[top]=p;k=1; break;//为左孩子结点
case ')':top--;break;
case ',':k=2; break; //为右孩子结点
default:p=new BTNode();
p->data=ch;p->lchild=p->rchild=NULL;
if (bt==NULL) //*p为二叉树的根结点
bt=p;
else //已建立二叉树根结点
{ switch(k)
{
case 1:St[top]->lchild=p;break;
case 2:St[top]->rchild=p;break;
}
}
}
j++;
ch=str[j];
}
}
// Traverse by levels and print with levels
void LevelOrder(BTNode *&bt)
{
BTNode *p;
BTNode *qu[MaxSize];
int curlevCount = 1, nextlevCount = 0; // 当前层次:只有根结点,层次结点数为1/Current level: root node, so curlevCount = 1
int front, rear;
front = rear = 0;
rear ++;
qu[rear] = bt;
while(front != rear)
{
front = (front + 1) % MaxSize;
p = qu[front];
cout<<p->data<<" ";
curlevCount --; // p(头结点)移动,结点值出队,当前层次结点数自减/p(front) moved, current level counts --
if(p->lchild != NULL)
{
rear = (rear + 1) % MaxSize;
qu[rear] = p->lchild;
nextlevCount ++; // 将下一层次结点入队并统计下一层次结点数/Push next level nodes to qu, count the num of next level
}
if(p->rchild != NULL)
{
rear = (rear + 1) % MaxSize;
qu[rear] = p->rchild;
nextlevCount ++;
}
if(curlevCount == 0) // p(头结点)移动了层次结点数,当前层次结点数归零,层次变化/p(front) moved level-num steps, goes to 0
{
cout<<endl;
curlevCount = nextlevCount; // 将原来的下一层次结点数赋给当前层次结点计数,开始计数当前层次的下一层次的结点数/Gives the original next-level-num to curlevCount, starts cont steps of this level
nextlevCount = 0;
}
}
}
void DestroyBTree(BTNode *&bt) //销毁二叉链
{ if (bt!=NULL)
{ DestroyBTree(bt->lchild);
DestroyBTree(bt->rchild);
delete bt;
}
}
int main()
{
char tree[MaxSize];
cin>>tree;
BTNode *bt;
CreateBTree(bt,tree);
LevelOrder(bt);
cout<<endl;
DestroyBTree(bt);
return 0;
}
说明
此篇仅做交流学习之用,相关内容学习中,不能保证一定准确或者最优。还请多多指教。