实验四 树
一、 实验目的
1.熟悉二叉树的链式存储结构
2.掌握二叉树的建立、深度优先递归遍历等算法
3.能够利用遍历算法实现一些应用
二、实验内容
2.采用二叉链表结构存储一棵二叉树,编写一个算法删除该二叉树中数据值为x的结点及其子树,并且输出被删除的子树。(文件夹:习题12_15)
//二叉链表的结构类型定义.h
const int maxsize=1024;
typedef char datatype;
typedef struct node
{
datatype data;
struct node *lchild,*rchild;
}bitree;
//二叉树的建立.h
bitree*creattree()
{
datatype ch;
bitree*Q[maxsize];
int front,rear;
bitree*root,*s;
root=NULL;
front=1;rear=0;
while((ch=getchar())!='#')
{
s=NULL;
if(ch!='@')
{
s=new bitree;
s->data=ch;
s->lchild=NULL;
s->rchild=NULL;
}
rear++;
Q[rear]=s;
if(rear==1)root=s;
else
{
if(s&&Q[front])
if(rear%2==0)Q[front]->lchild=s;
else Q[front]->rchild=s;
if(rear%2==1)front++;
}
}
return root;
}
//二叉树的输出.h
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using std::cout;
void preorder(bitree*p)
{
if(p!=NULL)
{
cout<<p->data;
if(p->lchild!=NULL||p->rchild!=NULL)
{
cout<<"(";
preorder(p->lchild);
if(p->rchild!=NULL)cout<<",";
preorder(p->rchild);
cout<<")";
}
}
}
//删除二叉树结点的主程序文件.cpp
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include"二叉链表的结构类型定义.h"
#include"二叉树的建立.h"
#include"二叉树的输出.h"
#include"删除结点和子树.h"
using std::cin;
using std::cout;
using std::endl;
int main()
{
bitree*root;
datatype x;
cout<<"请输入二叉树的结点,按先序序列输入,输入“@”表示结点为空,输入“#”结束输入:"<<endl;
root=creattree();
preorder(root);
cout<<endl;
cout<<"请输入需要删除的子树结点:"<<endl;
cin>>x;
root=delsubtree(root,x);
cout<<"删除子树后的二叉树是:"<<endl;
preorder(root);
cout<<endl;
system("PAUSE");
return 0;
}
//删除结点和子树.h
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
void Destroy( bitree * R );
bitree * delsubtree( bitree * root , datatype x )
{
if( root!=NULL )
{
root->lchild = delsubtree( root->lchild , x );
root->rchild = delsubtree( root->rchild , x );
if( root->data == x )
{
Destroy( root );
return NULL;
}
else
{
return root;
}
}
else
{
return root;
}
}
void Destroy( bitree * R )
{
if( R != NULL )
{
Destroy( R->lchild );
Destroy( R->rchild );
delete R;
}
}