请实现两棵树是否相等的比较,相等返回,否则返回其他值,并说明算法复杂度。
数据结构为:
typedef struct_TreeNode{
char c;
TreeNode *leftchild;
TreeNode *rightchild;
}TreeNode;
函数接口为:int CompTree(TreeNode* tree1,TreeNode* tree2);
注:A、B两棵树相等当且仅当Root->c==RootB–>c,而且A和B的左右子树相等或者左右互换相等。
解答:(注,这段代码没经过测试,很可能有问题,欢迎讨论哦)
/*
* FileName: CompBinTree.cpp
* Type: C++
* Copyright: (c) 2009 Jingyi Xiao
* Authors: Jingyi Xiao
* Description:
* NOTE: !!!! This is not been tested, maybe this is not correct !!!!
*/
#include iostream
#include cstdlib
using namespace std;
typedef struct BinTree{
int data;
BinTree * leftChild;
BinTree * rightChild;
};
int CompBinTree (BinTree * tree1, BinTree * tree2){ // 嘿嘿,一句return搞定~
return (!tree1 && !tree2) ||
(
tree1 && tree2 && tree1->data == tree2->data &&
(
(CompBinTree(tree1->leftChild, tree2->leftChild) &&
CompBinTree(tree1->rightChild, tree2->rightChild)) ||
(CompBinTree(tree1->leftChild, tree2->rightChild) &&
CompBinTree(tree1->rightChild, tree2->leftChild))
)
);
}
This entry was posted on 星期三, 十月 7th, 2009 at 2:08 下午 and is filed under 好代码、思想、算法, 我的好codes, 百度试题解答. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
10 Responses to “百度试题讲解:两棵树是否相等的比较”
Iron_Feet 说:
2009年10月11日 于 1:20 下午
好像你的接法是有问题的。
你应该把左右交换情况分开来考虑的。你这样写会出现问题。
比方说
A: 1 B: 1
2 3 2 3
4 5 5 4
如果用你的算法也会被判断为正确。你的代码帮两种情况混在一起考虑的。