二叉树

头文件:

#ifndef bitree_h
#define bitree_h


struct node
{
char data;
node *lchile, *rchile;
};


 class bitree
 {
public:
bitree(){root=great(root);}
~bitree(){release(root);}
void protree(){protree(root);}
void intree(){intree(root);}
void posttree(){posttree(root);}
private:
node *root;
node *great(node *bt);
void release(node *bt);
void protree(node *bt);
void intree(node *bt);
void posttree(node *bt);
 };
#endif




函数定义:

#include<iostream>
#include"head.h"
using namespace std;


node *bitree::great(node *bt){
char ch;
cout<<"please input a tree's number:"<<endl;
cout<<"input '#' is null"<<endl;
cin>>ch;
if(ch=='#')return NULL;
else{
bt=new node;
bt->data=ch;
bt->lchile=great(bt->lchile);
bt->rchile=great(bt->rchile);
}
return bt;
}


void bitree::release(node *bt){


if(bt!=NULL){
release(bt->lchile);
release(bt->rchile);
delete bt;
}
}


void bitree::protree(node *bt){
if(bt==NULL)return;
else{
cout<<bt->data<<" ";
protree(bt->lchile);
protree(bt->rchile);
}
}


void bitree::intree(node *bt){
if(bt==NULL)return;
else{
intree(bt->lchile);
cout<<bt->data<<" ";
intree(bt->rchile);
}
}


void bitree::posttree(node *bt){
if(bt==NULL)return;
else{
posttree(bt->lchile);
posttree(bt->rchile);
cout<<bt->data<<" ";
}
}


main函数:

#include<iostream>
#include"head.h"
using namespace std;


void main(){
bitree t;
system("cls");
cout<<"---------------------------------------"<<endl;
cout<<"     1 前序遍历        2 中序遍历      "<<endl;
cout<<"     3 前序遍历        0 退出          "<<endl;
cout<<"---------------------------------------"<<endl;
int a;
cout<<"选择其中一项进行:";
cin>>a;
while(a!=0){
switch(a){
case 1:cout<<"--------前序遍历-------"<<endl;
t.protree();
cout<<endl;
break;
case 2: cout<<"--------中序遍历-------"<<endl;
t.intree();
cout<<endl;
break;
case 3:cout<<"--------后序遍历-------"<<endl;
t.posttree();
cout<<endl;
break;
default: cout<<endl;
cout<<"请输入正确的编号"<<endl;
break;
}
system("pause");
system("cls");
cout<<"---------------------------------------"<<endl;
cout<<"     1 前序遍历        2 中序遍历      "<<endl;
cout<<"     3 前序遍历        0 退出          "<<endl;
cout<<"---------------------------------------"<<endl;
cout<<"选择其中一项进行:";
cin>>a;
}
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值