题目:
请实现两棵树是否相等的比较,相等返回1,否则返回其他值,并说明算法复杂度。
数据结构为:
typedef struct_TreeNode{
char c;
TreeNode *leftchild;
TreeNode *rightchild;
}TreeNode;
函数接口为:int CompTree(TreeNode* tree1,TreeNode* tree2);
注:A、B两棵树相等当且仅当Root->c==RootB-->c,而且A和B的左右子树相等或者左右互换相等。
更多方法请见:
http://hi.baidu.com/mianshiti/blog/item/1070b78ce2ece2f1513d92e7.html
int CompTree(TreeNode* tree1,TreeNode* tree2)
{
if (tree1 == NULL && tree2 == NULL)
{
return 1;
}
if (tree1 == NULL || tree2 == NULL)
{
return 0;
}
if (tree1.c != tree2.c)
{
retrun 0;
}
if (CompTree(tree1->leftchild, tree2->leftchil) &&
CompTree(tree1->rightchild, tree2->rightchild) ||
CompTree(tree1->leftchild, tree2->rightchild) &&
CompTree(tree1->rightchild, tree2->leftchild))
{
return 1;
}
}