二叉树的基本操作
来源:互联网 发布:查域名对应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);
}
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- nowrap
- myeclipse svn 分支合并
- 库函数调用和系统调用的区别
- printf、sprintf与fprintf 的用法区分
- 最长上升子序列(LIS)(HDU 1025)
- 二叉树的基本操作
- MongoDB中关于查询条件中包含集合中字段的查询
- C++中两个类相互包含引用问题
- MySQL安装 + VS2010配置
- 嵌入式开发基础--Linux常用命令介绍
- Mysql自己常用命令笔记
- 改进delphi中的RoundTo函数
- ORA-16198: LGWR received timedout error from KSR
- java http大文件上传,断点续传项目研究,Github上传源代码