版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZKX2015/article/details/49978327
头文件和功能函数与上篇博文相同
主函数:
#include "btree.h"
int Nodes(BTNode *b)
{
if (b==NULL)
return 0;
else
return Nodes(b->lchild)+Nodes(b->rchild)+1;
}
void DispLeaf(BTNode *b)
{
if (b!=NULL)
{
if (b->lchild==NULL && b->rchild==NULL)
printf("%c ",b->data);
else
{
DispLeaf(b->lchild);
DispLeaf(b->rchild);
}
}
}
int LeafNodes(BTNode *b)
{
int num1,num2;
if (b==NULL)
return 0;
else if (b->lchild==NULL && b->rchild==NULL)
return 1;
else
{
num1=LeafNodes(b->lchild);
num2=LeafNodes(b->rchild);
return (num1+num2);
}
}
int Level(BTNode *b,ElemType x,int h)
{
int l;
if (b==NULL)
return 0;
else if (b->data==x)
return h;
else
{
l=Level(b->lchild,x,h+1);
if (l==0)
return Level(b->rchild,x,h+1);
else
return l;
}
}
int Like(BTNode *b1,BTNode *b2)
{
int like1,like2;
if (b1==NULL && b2==NULL)
return 1;
else if (b1==NULL || b2==NULL)
return 0;
else
{
like1=Like(b1->lchild,b2->lchild);
like2=Like(b1->rchild,b2->rchild);
return (like1 & like2);
}
}
int main()
{
BTNode *b;
CreateBTNode(b,"A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))");
printf("(1)二叉树节点个数: %d ", Nodes(b));
printf("(2)二叉树中所有叶子节点是: ");
DispLeaf(b);
printf(" ");
printf("(3)二叉树b的叶子节点个数: %d ",LeafNodes(b));
printf("(4)值为\'K\'的节点在二叉树中出现在第 %d 层上n ",Level(b,'K',1));
BTNode *b1, *b2, *b3;
CreateBTNode(b1,"B(D,E(H(J,K(L,M(,N)))))");
CreateBTNode(b2,"A(B(D(,G)),C(E,F))");
CreateBTNode(b3,"u(v(w(,x)),y(z,p))");
if(Like(b1, b2))
printf("(5)b1和b2相似\n");
else
printf("(5)b1和b2不相似\n");
if(Like(b2, b3))
printf(" b2和b3相似\n");
else
printf(" b2和b3不相似\n");
DestroyBTNode(b1);
DestroyBTNode(b2);
DestroyBTNode(b3);
DestroyBTNode(b);
return 0;
}
运行结果: