本文内容
- 环境
- 链式二叉树节点
- 链式二叉树是否相同
- 测试
本文主要描述判断两个链式二叉树是否相同,所谓相同,结构要相同,节点的值也要相同。
环境
- codeblock 12.11
- Windows 7 旗舰版 64位
链式二叉树节点
typedef struct BiTreeNode *BiTreePrt;
typedef BiTreePrt BiTree;
struct BiTreeNode
{
TElementType Element;
BiTreePrt Left;
BiTreePrt Right;
};
链式二叉树是否相同
int Like( BiTree T1, BiTree T2 )
{
int like1,like2;
if(T1==NULL && T2==NULL) return 1;
else if(T1==NULL || T2==NULL) return 0;
else
{
like1=Like(T1->Left, T2->Left);
like2=Like(T1->Right,T2->Right);
return (like1 && like2);
}
}
测试
BiTree T1 = NULL, T2 = NULL, T3 = NULL;
int i,n;
TElementType a1[] = {1, 2, -1, -1, 3, -1, -1};
TElementType a2[] = {10, 20, -1, 30, -1, -1, -1};
TElementType a3[] = {10, 20, -1, 30, -1, -1, -1};
i=0;
n=7;
T1 = CreateBiTreeArray(a1, &i, n);
printf("\nT1 二叉树\n");
printf("先序遍历:(高度 %d),是否为空 %d\n", BiTreeDepth(T1));
BiTreePreOrder(T1, PrintBiTree);
printf("\n--END.\n\n");
i=0;
n=7;
T2 = CreateBiTreeArray(a2, &i, n);
printf("\nT2 二叉树\n");
printf("中序遍历:(高度 %d),是否为空 %d\n", BiTreeDepth(T2));
BiTreeInOrder(T2, PrintBiTree);
printf("\n--END.\n\n");
i=0;
n=7;
T3 = CreateBiTreeArray(a3, &i, n);
printf("\nT3 二叉树\n");
printf("后序遍历:(高度 %d),是否为空 %d\n", BiTreeDepth(T3));
BiTreePostOrder(T3, PrintBiTree);
printf("\n--END.\n\n");
printf("\nT1 和 T2 是否相同:%d\n", Like(T1, T2));
printf("\nT2 和 T3 是否相同:%d\n", Like(T2, T3));
MakeEmptyBiTree(T1);
MakeEmptyBiTree(T2);
MakeEmptyBiTree(T3);