二叉树的基本操作

来源:互联网 发布:查域名对应IP 编辑:程序博客网 时间:2024/06/06 20:59

//二叉树的基本操作

#include <stdio.h>

#include <malloc.h>

#define MAXSIZE 100

typedef char elemtype;

typedef struct node

{

elemtype data;

struct node *lchild;

struct node *rchild;

}BTNode;

void CreateBTNode(BTNode **b,elemtype *str)

{

BTNode *st[MAXSIZE],*p=NULL;

int top=-1,k,i;

*b=NULL;

elemtype ch;

for(i=0;(ch=str[i])!='\0';i++)

{

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;

}

}

}

}

}

BTNode *FindNode(BTNode *b,elemtype x)

{

BTNode *p=NULL;

if(!b||b->data==x)

return b;

else

{

p=FindNode(b->lchild,x);

if(p)

           return p;

else

return FindNode(b->rchild,x);

}

}

BTNode *LchildNode(BTNode *p)

{

return p->lchild;

}

BTNode *RchildNode(BTNode *p)

{

return p->rchild; 

}

int Depth(BTNode *b)

{

int num1,num2;

if(!b)

return 0;

else if(b->lchild==NULL&&b->rchild==NULL)

return 1;

else

{

num1=Depth(b->lchild);

num2=Depth(b->rchild);

return (num1>num2)?(num1+1):(num2+1);

}

}

void DispBTNode(BTNode *b)

{

if(b)

{

printf("%c",b->data);

if(b->lchild||b->rchild)

{

printf("(");

DispBTNode(b->lchild);

if(b->rchild)

{

printf(",");

DispBTNode(b->rchild);

}

printf(")");

}

}

}

int Nodes(BTNode *b)

{

int num1,num2;

if(!b)

return 0;

else if(b->lchild==NULL&&b->rchild==NULL)

return 1;

else

{

num1=Nodes(b->lchild);

num2=Nodes(b->rchild);

return (num1+num2+1);

}

}

int LeafNodes(BTNode *b)

{

int num1,num2;

if(!b)

return 0;

else if(b->lchild==NULL&&b->rchild==NULL)

return 1;

else

{

       num1=LeafNodes(b->lchild);

   num2=LeafNodes(b->rchild);

   return (num1+num2);

}

}

void DestroyBTNode(BTNode *b)

{

if(b)

{

DestroyBTNode(b->lchild);

DestroyBTNode(b->rchild);

free(b);

}

}

void main()

{

BTNode *b,*p,*lp,*rp;

elemtype *str="A(B(D,E),C(F))";

CreateBTNode(&b,str);

printf("输出二叉树:");

DispBTNode(b);

printf("\n");

printf("B节点:");

p=FindNode(b,'B');

    if(p)

{

lp=LchildNode(p);

if(lp)

printf("左孩子为:%c  ",lp->data);

else

printf("无左孩子");

rp=RchildNode(p);

if(rp)

printf("右孩子为:%c\n",rp->data);

else

printf("无右孩子\n");

}

printf("树的深度:%d\n",Depth(b));

    printf("树的节点个数:%d\n",Nodes(b));

printf("树的叶子节点个数:%d\n",LeafNodes(b));

printf("释放二叉树\n");

DestroyBTNode(b);

}

 

0 0
原创粉丝点击