关于二叉树 层序遍历和树状输出 的问题

Naruto 2011-06-08 06:27:56
小弟刚学数据结构,学到了二叉树。

有两个问题搞不清楚:

1、怎么把二叉树按层输出,比如输出为:
A
BC
DEG
就这样一层一层的输出,至少知道每层有几个元素。

2、怎么树状输出二叉树,就是屏幕上竖着按二叉树树状输出。
...全文
850 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
nuptxxp 2011-06-11
  • 打赏
  • 举报
回复
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;
}
}

nuptxxp 2011-06-11
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 kadingxiaodi 的回复:]
#include<stdio.h> //二叉树的层序遍历。
#include<stdlib.h>
typedef struct BiNode
{
char data;
BiNode *lchild,*rchild;
} *BiTree;
BiTree queue[100]; //队列当中存的是指向结构体的指针,而不是通常的整形或字符型的数据。
int front,rear;
……
[/Quote]
LS还有两个bug,
1.输入如果用scanf,会把回车读进去,应该用cin
2.没有考虑空树的情形,比如只输入#,这样会导致指针越界
Oo纳兰筱DoO 2011-06-08
  • 打赏
  • 举报
回复
#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);
}
Naruto 2011-06-08
  • 打赏
  • 举报
回复
[Quote=引用楼主 zhangkaihang 的回复:]
小弟刚学数据结构,学到了二叉树。

有两个问题搞不清楚:

1、怎么把二叉树按层输出,比如输出为:
A
BC
DEG
就这样一层一层的输出,至少知道每层有几个元素。

2、怎么树状输出二叉树,就是屏幕上竖着按二叉树树状输出。
[/Quote]

恩恩,能贴上程序就好了!!!!
nuptxxp 2011-06-08
  • 打赏
  • 举报
回复
1.这属于层次遍历,可以使用一个队列,储存各节点,再按顺序输出
2.关于打印方面,主要是格式问题,你注意空格与那个斜线的输出位置就行(关于打印,本来思考能不能用递归,但没想出来)

33,010

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧