把我的 C 作业贴出来 实验四 树——2

实验四

一、 实验目的

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值