关于二叉树 层序遍历和树状输出 的问题
小弟刚学数据结构,学到了二叉树。
有两个问题搞不清楚:
1、怎么把二叉树按层输出,比如输出为:
A
BC
DEG
就这样一层一层的输出,至少知道每层有几个元素。
2、怎么树状输出二叉树,就是屏幕上竖着按二叉树树状输出。
[解决办法]
#include<stdio.h> //二叉树的层序遍历。
#include<stdlib.h>
typedef struct BiNode
{
char data;
BiNode *lchild,*rchild;
} *BiTree;
BiTree queue[100]; //队列当中存的是指向结构体的指针,而不是通常的整形或字符型的数据。
int front,rear;
BiTree CreateTree() //建立二叉树
{
BiTree root;
char ch;
scanf("%c",&ch);
if(ch=='#') root=NULL;
else{
root=new BiNode;
root->data=ch;
root->lchild=CreateTree();
root->rchild=CreateTree();
}
return root;
}
void LayerOrder(BiTree T)//层序遍历二叉树(进出队列元素都依赖于front)
{
front=rear=0;
queue[++rear]=T;
while(front!=rear)
{
printf("%c",queue[++front]->data);
if(queue[front]->lchild) queue[++rear]=queue[front]->lchild;
if(queue[front]->rchild) queue[++rear]=queue[front]->rchild;
}
}
void main()
{
BiTree root;
root=CreateTree();
LayerOrder(root);
}
[解决办法]
void LayerOrder(BiTree T)//层序遍历二叉树(进出队列元素都依赖于front)
{
if(T==NULL)
return;//可以加上这一句就完美了
front=rear=0;
queue[++rear]=T;
while(front!=rear)
{
printf("%c",queue[++front]->data);
if(queue[front]->lchild) queue[++rear]=queue[front]->lchild;
if(queue[front]->rchild) queue[++rear]=queue[front]->rchild;
}
}