posts - 352,  comments - 53,  views - 92万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

题目:

请实现两棵树是否相等的比较,相等返回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;
    }
}
posted on   dartagnan  阅读(1912)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示