二叉树的基本运算
由str创建二叉链
{
BTNode *St[MaxSize],*p=NULL;
int top=-1,k,j=0;
char ch;
bt=NULL; /*建立的二叉树初始时为空*/
ch=str[j];
while (ch!='\0') /*str未扫描完时循环*/
{
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;
bt=p;
else /*已建立二叉树根结点*/
{ switch(k)
{
case 1:St[top]->lchild=p;break;
}
}
}
j++;
ch=str[j];
}
}
求二叉树的结点个数
int NodeCount(BTNode *bt) /*求二叉树bt的结点个数*/
{
int num1,num2;
if (bt==NULL) /*空树结点个数为0*/
return 0;
else
{ num1=NodeCount(bt->lchild); /*求出左子树的结点数*/
num2=NodeCount(bt->rchild); /*求出右子树的结点数*/
return (num1+num2+1);
}
}
以括号表示法输出二叉树
{
if (bt!=NULL)
printf("%c",bt->data);
if (bt->lchild!=NULL || bt->rchild!=NULL)
{
printf("(");
DispBTree(bt->lchild); /*递归处理左子树*/
if (bt->rchild!=NULL)
printf(",");
DispBTree(bt->rchild); /*递归处理右子树*/
printf(")");
}
}
}
main
void main()
{
BTNode *bt;
CreateBTree(bt,"A(B(D,E(G,H)),C(,F(I)))"); /*构造图5.10(a)所示的二叉树*/
printf("二叉树bt:");DispBTree(bt);printf("\n");
printf("bt的高度:%d\n",BTHeight(bt));
printf("bt的结点数:%d\n",NodeCount(bt));
printf("bt的叶子结点数:%d\n",LeafCount(bt));
printf("bt凹入表示:\n");DispBTree1(bt);printf("\n");