请实现两棵树是否相等的比较,相等返回,否则返回其它值,并说明算法复杂度

来源:互联网 发布:淘宝举报卖家有用吗 编辑:程序博客网 时间:2024/05/17 15:39
数据结构为:
typedef struct __TreeNode {
char c;
TreeNode *leftchild;
TreeNode *rightchild;
} TreeNode;
函数接口为:int CompTree(TreeNode* tree1, TreeNode* tree2);

注:A、B两棵树相等当且仅当RootA->c==RootB->c,而且A和B的左右子树对应相等或者左右互换后相等。


#include "stdio.h"#include<malloc.h>typedef struct TreeNode{char c;TreeNode *leftChild;TreeNode *rightChild;}TreeNode;int compTree(TreeNode *tree1, TreeNode *tree2){if(!tree1 && !tree2) return 1;if((tree1 && !tree2) ||(!tree1 && tree2)) return 0;if(tree1 && tree2) {if(tree1->c==tree2->c){if(compTree(tree1->leftChild, tree2->leftChild))returncompTree(tree1->rightChild, tree2->rightChild); else if(compTree(tree1->rightChild, tree2->leftChild)) return compTree(tree1->leftChild, tree2->rightChild);}}return 0;}int createTree(TreeNode *T){char ch;scanf("%c",&ch);if(ch=='@') T=NULL;else{   T=(TreeNode *)malloc(sizeof(TreeNode));   T->c=ch;   createTree(T->leftChild);   createTree(T->rightChild);}return 1;}void main(){TreeNode * T1;TreeNode * T2;int t1,t2;printf("请依次输入:ABC@@DE@G@@F@@@,@表示空格\n");t1=createTree(T1);if(t1) printf("T1Initial done!\n");t2=createTree(T2);if(t2) printf("T2Initial done!\n");t1 = compTree(T1,T2);if(t1) printf("T1 and T2 equals!\n"); else printf("T1 and T2 not equals!\n");}