实验四 二叉树的基本操作
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
实用文档
实验四二叉树的基本操作
一、实验目的
1.进一步掌握指针变量的含义。
2.掌握二叉树的结构特征,以及各种存储结构的特点及使用范围。
3.掌握用指针类型描述、访问和处理二叉树的运算。
二、实验要求
1、设计二叉树的基本操作;
2、写出相应程序;
3、保存和打印出程序的运行结果,并结合程序进行分析。
三、实验内容
给出一个可进行二叉树基本操作的完整程序,具有以下功能:
(1)根据输入字符序列,建立二叉树;
(2)用递归算法实现输出二叉树的前序、中序、后序遍历序列;
(3)求二叉树的高度。
附加题: (有时间可继续完成下面内容)
(4)用非递归算法实现输出二叉树的前序、中序遍历序列;
(5)求二叉树的叶子个数;
(6)求度为1的结点的个数;
算法:
四、程序代码
建树,遍历,求树高
#include
#include
#include
typedef struct Node{
char data;
struct Node * lchild;
struct Node * rchild;
}Node,*Tree;
void a(Tree & t){ //构造二叉树
char ch;
scanf("%c",&ch);
if(ch=='.')
实用文档
t=NULL;
else{
t=(Tree)malloc(sizeof(Node));
t->data=ch;
a(t->lchild);
a(t->rchild);
}
return;
}
void b(Tree & t){ //先序遍历
if(t){
printf("%c",t->data);
b(t->lchild);
b(t->rchild);
}
}
void c(Tree & t){ //中序遍历
if(t){
c(t->lchild);
printf("%c",t->data);
c(t->rchild);
}
}
void d(Tree & t){ //后序遍历
if(t){
d(t->lchild);
d(t->rchild);
printf("%c",t->data);
}
}
int max(int x,int y)
{
return x>y?x:y;
}
int high(Tree & t)
{
if(t==NULL)
return 0;
else
return max(high(t->lchild),high(t->rchild))+1;
}
int main(){
Tree t;
printf("请输入二叉树:\n");
a(t);
printf("\n先序遍历 \n\n");
b(t);
printf("\n\n中序遍历 \n\n");
c(t);
printf("\n\n后序遍历 \n\n");
d(t);
printf("\n\n树高为:%d",high(t));
}
非递归先序,中序遍历,求叶子节点的个数,求度为1的节点的个数
#include
#include
#include
typedef struct Node{
char data;
struct Node * lchild;
struct Node * rchild;
}Node,*Tree;
void a(Tree & t){ //构造二叉树
char ch;
scanf("%c",&ch);
if(ch=='.')
t=NULL;
else{
t=(Tree)malloc(sizeof(Node));
t->data=ch;
a(t->lchild);
a(t->rchild);
}
return;
}
void b(Tree t)
{
Tree stack[20], p;
int top = -1;
if (t != NULL)
{
top++;
stack[top] = t;
while (top > -1)
{
p = stack[top];
top--;
printf("%c ", p->data);
if (p->rchild != NULL)
{
top++;
stack[top] = p->rchild; }
if (p->lchild != NULL)
{
top++;
stack[top] = p->lchild; }
}
printf("\n");
}
}
void c(Tree t)
{
Tree stack[20], p;
int top = -1;
if (t != NULL)
{
p = t;
while (top > -1 || p != NULL) {
while (p != NULL)
{
top++;
stack[top] = p;
p = p->lchild;
}