自己写的二叉树,输入先序遍历中序遍历后序遍历和求深度
#define ok 1#define error 0
#define overflow -2
#define elemtype char
typedef int status;
typedef struct bitnode{
elemtype data;
struct bitnode *lchild,*rchild;
}bitnode,*bitree;
#include<iostream.h>
#include<stdlib.h>
#include"status.h"
void disp()
{
cout<<"\n"<<"1.构造一个二叉树\n";
cout<<"2.先序遍历\n";
cout<<"3.中序遍历\n";
cout<<"4.后序遍历\n";
cout<<"5.求深度\n";
cout<<"6.退出\n";
}
void creatbitree(bitree &t)//构造一个二叉树
{
char ch;
cin>>ch;
if(ch=='#')t=NULL;
else
{
t=(bitree)malloc(sizeof(bitnode));
t->data=ch;
creatbitree(t->lchild);
creatbitree(t->rchild);
}
}
void preorder(bitree t)//先序遍历
{
if(t!=NULL)
{
cout<<t->data;
if(t->lchild)
preorder(t->lchild);
if(t->rchild)
preorder(t->rchild);
}
}
void inorder(bitree t)//中序遍历
{
if(t!=NULL)
{
preorder(t->lchild);
cout<<t->data;
preorder(t->rchild);
}
}
void postorder(bitree t)//后序遍历
{
if(t!=NULL)
{
preorder(t->lchild);
preorder(t->rchild);
cout<<t->data;
}
}
int deep(bitree t)//求深度
{
int l=1,r=1;
if(!t)return 0;
else
{
l=deep(t->lchild);
r=deep(t->rchild);
if(l>r)
return l+1;
else return r+1;
}
}
void main()
{
int n;
bitree t;
while(1)
{
disp();
cin>>n;
switch(n)
{
case 1:
creatbitree(t);break;
case 2:
preorder(t);break;
case 3:
inorder(t);break;
case 4:
postorder(t);break;
case 5:
deep(t);cout<<"深度为"<<deep(t)<<"\n";br eak;
case 6:
exit(1);break;
}
}
}
[此贴子已经被作者于2016-6-8 15:13编辑过]