#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node* lchild;
struct node* rchild;
}BTNode;
void GreatBTree(BTNode *&b,char *str);
void DispBTree(BTNode *b);
void DestroyBTree(BTNode * &b);
BTNode *FindNode(BTNode *b,char x);
BTNode *LchildNode(BTNode *p);
int BTHeight(BTNode *b);
int main()
{
BTNode *b,*p;
char str[100],x='B';
scanf("%s",str);
GreatBTree(b,str);
DispBTree(b);
p=FindNode(b,x);
printf("%c\n",p->data);
p=LchildNode(b);
printf("%c\n",p->data);
//int a;
printf("%d\n",BTHeight(b));
return 0;
}
void GreatBTree(BTNode *&b,char *str)
{
BTNode *St[100],*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 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(")");
}
}
}
void DestroyBTree(BTNode* &b)
{
if(b!=NULL)
{
DestroyBTree(b->lchild);
DestroyBTree(b->rchild);
free(b);
}
}
BTNode *FindNode(BTNode *b,char 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)
{
return p->lchild;
}
int BTHeight(BTNode *b)
{
int lchild,rchild;
if(b==NULL) return 0;
else
{
lchild=BTHeight(b->lchild);
rchild=BTHeight(b->rchild);
return (lchild>rchild)?(lchild+1):(rchild+1); //不能用lchild++
}
}
构建二叉树(数据结构,李春葆)
猜你喜欢
转载自blog.csdn.net/foolishpichao/article/details/83118213
今日推荐
周排行