您的位置:首页 > 其它

第九周——项目3 - 利用二叉树遍历思想解决问题

2017-10-28 22:31 621 查看
/*烟台大学计算机学院

文件名称:btree

作者:董玉祥

完成日期: 2017 10 28
问题描述:(1)计算二叉树节点个数;
  (2)输出所有叶子节点;
  (3)求二叉树b的叶子节点个数;
  (4)设计一个算法Level(b,x,h),返回二叉链b中data值为x的节点的层数。
  (5)判断二叉树是否相似(关于二叉树t1和t2相似的判断:①t1和t2都是空的二叉树,相似;②t1和t2之一为空,另一不为空,则不相似;③t1的左子树和t2的左子树是相似的,且t1的右子树与t2的右子树是相似的,则t1和t2相似。)

*/
#include <stdio.h>
#include "btree.h"
int CountBtree(BTNode *b)
{   int lcount,rcount;
if(b==NULL)
return 0;
else
{
lcount=CountBtree(b->lchild);
rcount=CountBtree(b->rchild);
return (lcount+rcount+1);
}
}
bool YeBtree(BTNode *b)
{
if(b==NULL)
return false;
else
{
if(b->lchild==NULL&&b->rchild==NULL)

printf("%c",b->data);
YeBtree(b->lchild);
YeBtree(b->rchild);
}

}
int CountYeBtree(BTNode *b)
{
int yelcount,yercount;
if(b==NULL)
return 0;
else if(b->lchild==NULL&&b->rchild==NULL)
return 1;
else
{
yelcount=CountYeBtree(b->lchild);
yercount=CountYeBtree(b->rchild);
return (yelcount+yercount);
}
}
int Level(BTNode *b,ElemType x,int h)
{
int i;
if(b==NULL)
return 0;
else if(b->data==x)
{
return h;
}
else
{
i=Level(b->lchild,x,h+1);
if(i==0)
Level(b->rchild,x,h+1);

else

return i;
}

}
bool sametree(BTNode *t1,BTNode *t2)
{   int i,j;
if(t1==NULL&&t2==NULL)
return true;
else if(t1==NULL || t2==NULL)
{
return false;
}
else
{
i=sametree(t1->lchild,t2->lchild);
j=sametree(t1->rchild,t2->rchild);
return (i&j);
}
}
int  main()

{
BTNode *p;
char x;
CreateBTNode(p,"A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))");
printf("节点个数%d\n",CountBtree(p));
printf("输出叶子节点:");
YeBtree(p);
printf("\n");
printf("叶子节点个数:%d\n",CountYeBtree(p));
printf("二叉树结点层数:%d\n",Level(p,'K',1));
BTNode *q,*p1;
CreateBTNode(q,"u(v(w(,x)),y(z,p))");
CreateBTNode(p1,"A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))");
if(sametree(p,p1))
printf("相似");
else
printf("不相似");

if(sametree(p,q))
printf("相似");
else
printf("不相似");

}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: