数据结构与算法之二叉链树
数据结构
李春葆系列
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#define MaxSize 100
using namespace std;
typedef char ElemType ;
typedef struct node
{
ElemType data;
struct node * lchild;
struct node * rchild;
}BTNode;
void CreateBTree(BTNode *&b,char *str)// 创造二叉树
{
BTNode *St[MaxSize],*p;
int top=-1,k,j=0;
char ch;
b=NULL;
ch=str[j];
while(ch!='\0')
{
switch(ch)
{
case'(':
top++;
St[top]=p;
k=1;
break;
case')':
top--;
break;
case',':
k=2;
break;
default:
p=(BTNode *)malloc(sizeof(BTNode));
p->data = ch;
p->lchild = p->rchild = NULL;
if(b==NULL)
{
b=p;
}
else
{
switch(k)
{
case 1:St[top]->lchild=p;break;
case 2:St[top]->rchild=p;break;
}
}
}
j++;
ch=str[j];
}
}
void DestroyBTree(BTNode *& b)//销毁二叉树
{
if(b!=NULL)
{
DestroyBTree(b->lchild);
DestroyBTree(b->rchild);
free(b);
}
}
BTNode *FindNode(BTNode * b,ElemType x)//查找结点
{
BTNode *p;
if(b==NULL)
{
return NULL;
}
else if(b->data==x)
{
return b;
}
else
{
p=FindNode(b->lchild,x);
if(p!=NULL)
{
return p;
}
else
{
return FindNode(b->rchild,x);
}
}
}
BTNode *LchildNode(BTNode *p)//返回结点p的左孩子结点
{
return p->lchild;
}
BTNode *RchildNode(BTNode *p)//返回结点p的右孩子结点
{
return p->rchild;
}
int BTHeight(BTNode *b)//求高度
{
if(b==NULL)
{
return (0);
}
else
{
return (BTHeight(b->lchild)>BTHeight(b->rchild))?(BTHeight(b->lchild)+1):(BTHeight(b->rchild)+1);
}
}
void DispBTree(BTNode *b)//输出二叉树
{
if(b!=NULL)
{
printf("%c",b->data);
if(b->lchild!=NULL||b->rchild!=NULL)
{
printf("(");
DispBTree(b->lchild);
if(b->rchild!=NULL)
{
printf(",");
}
DispBTree(b->rchild);
printf(")");
}
}
}
int main()
{ BTNode *b,*p;
CreateBTree(b,"A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))");
DispBTree(b);
p = FindNode(b, 'H');
if(p != NULL)
{ printf("\n");
printf("左孩子为%c\n", LchildNode(p)->data);
printf("右孩子为%c\n",RchildNode(p)->data);
}
else
{
printf("这是一个叶子结点,无孩子\n");
}
printf("树高:%d\n",BTHeight(b));
DestroyBTree(b);
printf("二叉树已经释放");
}