#include<iostream>
#include<malloc.h>
using namespace std;
typedef char ElemType;
typedef struct node
{
ElemType data;
struct node *lchild;//指向左孩子节点
struct node *rchild;//指向右孩子节点
}BTNode;
int Create(BTNode *&b)
{
b=(BTNode *)malloc(sizeof(BTNode));
ElemType ch;
cin>>ch;
if(ch=='#')
b=NULL;//如果字符为’#’,则表示空
else {
//判断指针是否创建成功
//if(!(b=(BTNode *)malloc(sizeof(BTNode))));
//return 1;
b->data=ch;
Create(b->lchild);
Create(b->rchild);
}
return 1;
}
void Disp(BTNode *b,int Layer)
{
if(b!=NULL)
{
Disp(b->rchild,Layer+1);
for(int i=0;i<Layer;i++)
cout<<" ";
cout<<b->data<<" ";
cout<<endl<<endl;
Disp(b->lchild,Layer+1);
}
}
void Destroy(BTNode *&b)
{
if(b!=NULL)
{
Destroy(b->lchild);
Destroy(b->rchild);
free(b);
}
}
BTNode *Find(BTNode *b,ElemType x)
{BTNode *p;
if(b==NULL)
return NULL;
else if(b->data==x)
return b;
else
{
p=Find(b->lchild,x);
if(p!=NULL)
return p;
else
return Find(b->rchild,x);
}
}
BTNode *Lchild(BTNode *p)
{
return p->lchild;
}
BTNode *Rchild(BTNode *p)
{
return p->rchild;
}
int Height(BTNode *b)
{
int lheight,rheight;
if(b==NULL)
return 0;
else{
lheight=Height(b->lchild);
rheight=Height(b->rchild);
return (lheight>rheight)?(lheight+1):(rheight+1);
}
}
//先序遍历二叉树
void PreOrder(BTNode *b)
{
if(b!=NULL)
{
cout<<b->data;
PreOrder(b->lchild);
PreOrder(b->rchild);
}
}
//中序遍历二叉树
void InOrder(BTNode *b)
{
if(b!=NULL)
{
InOrder(b->lchild);
cout<<b->data;
InOrder(b->rchild);
}
}
//后序遍历二叉树
void PostOrder(BTNode *b)
{
if(b!=NULL)
{
PostOrder(b->lchild);
PostOrder(b->rchild);
cout<<b->data;
}
}
int CountLeaf(BTNode *b)
{
if(b==NULL)
return 0;
else if(!b->lchild&&!b->rchild)
return 1;
else
return CountLeaf(b->lchild)+CountLeaf(b->rchild);
}
int Depth(BTNode *b)
{
int l,r;
if(b==NULL)
return NULL;
else
{
l=Depth(b->lchild);
r=Depth(b->rchild);
return(l>r)?(l+1):(r+1);
}
}
int main()
{
BTNode *b;
Create(b);
Disp(b,0);
cout<<endl<<"先序遍历 : ";
PreOrder(b);
cout<<endl<<"中序遍历 : ";
InOrder(b);
cout<<endl<<"后序遍历 : ";
PostOrder(b);
cout<<endl<<"叶子数是: "<<CountLeaf(b);
cout<<endl<<"深度是: "<<Depth(b);
return 0;
}
数据结构(二叉树)
最新推荐文章于 2023-06-03 11:00:15 发布