储存结构
struct BiNode
{
char data;
struct BiNode *lchild;
struct BiNode *rchild;
};
二叉树的建立
先序建立
struct BiNode *CreateBiTree1()
{
struct BiNode *T;
char ch;
scanf("%c",&ch);
if(ch==',') T=NULL;
else
{
T=(struct BiNode*)
malloc(sizeof(struct BiNode));
T->data=ch;
T->lchild=CreateBiTree1();
T->rchild=CreateBiTree1();
}
return T;
};
中序建立
struct BiNode *CreateBiTree2()
{
struct BiNode *T;
char ch;
scanf("%c",&ch);
if(ch==',') T=NULL;
else
{
T=(struct BiNode*)
malloc(sizeof(struct BiNode));
T->lchild=CreateBiTree2();
T->data=ch;
T->rchild=CreateBiTree2();
}
return T;
};
后序建立
struct BiNode *CreateBiTree3()
{
struct BiNode *T;
char ch;
scanf("%c",&ch);
if(ch==',') T=NULL;
else
{
T=(struct BiNode*)
malloc(sizeof(struct BiNode));
T->lchild=CreateBiTree3();
T->rchild=CreateBiTree3();
T->data=ch;
}
return T;
};
二叉树的遍历
遍历:
可做任何不改变树的结构的操作
,
每个节点均遍历
,
先序遍历
void PreOrderTraverse1(struct BiNode *T)
{
if(T!=NULL)
{
printf("%c",T->data); //visit(t) (访问根节点)
PreOrderTraverse1(T->lchild)
PreOrderTraverse1(T->rchild);
}
}
中序遍历
void PreOrderTraverse2(struct BiNode *T)
{
if(T!=NULL)
{
PreOrderTraverse2(T->lchild);
printf("%c",T->data); //visit(t) (访问根节点)
PreOrderTraverse2(T->rchild);
}
}
后序遍历
void PreOrderTraverse3(struct BiNode *T)
{
if(T!=NULL)
{
PreOrderTraverse3(T->lchild);
PreOrderTraverse3(T->rchild);
printf("%c",T->data);
}
}
遍历应用
计算二叉树的深度
int Depth(struct BiNode *T)
{
if(T==NULL) return 0;
else
{
int m,n;
m=Depth(T->lchild);
n=Depth(T->rchild);
if(m>n) return (m+1);
else return(n+1);
}
}
计算节点总数
int NodeCount(struct BiNode *T)
{
if(T==NULL) return 0;
else
{
return NodeCount(T->lchild)+
NodeCount(T->rchild)+1;
}
}
计算叶子总数
int LeadCount(struct BiNode *T)
{
if(T==NULL) return 0;
if(T->lchild == NULL&&T->rchild==NULL)
return 1;
else
return LeadCount(T->lchild)+LeadCount(T->rchild);
}