判断两棵树是否相等
2011-12-04 17:15
190 查看
题目:请实现两棵树是否相等的比较,相等返回1,否则返回其他值,并说明算法复杂度。
数据结构为:
函数接口为:int CompTree(TreeNode* tree1,TreeNode* tree2);
注:A、B两棵树相等当且仅当Root->c==RootB–>c,而且A和B的左右子树相等或者左右互换相等。
如果是单纯比较树则这个问题比较简单,这个地方有一个左右互换相等,需要特别处理一下:
如下图,就是相同的树,左右互换相等。
仔细分析一下,如果用递归算法,可以很简单的得到一个解:
对于2个孩子的节点,A与B是否相等等同于
compare(A.left, B.left) && compare(A.right, B.right) || compare(A.left, B.right) && compare(A.right, B.left)
实现程序如下:
数据结构为:
typedef struct_TreeNode{ char c; TreeNode *leftchild; TreeNode *rightchild; }TreeNode;
函数接口为:int CompTree(TreeNode* tree1,TreeNode* tree2);
注:A、B两棵树相等当且仅当Root->c==RootB–>c,而且A和B的左右子树相等或者左右互换相等。
如果是单纯比较树则这个问题比较简单,这个地方有一个左右互换相等,需要特别处理一下:
如下图,就是相同的树,左右互换相等。
仔细分析一下,如果用递归算法,可以很简单的得到一个解:
对于2个孩子的节点,A与B是否相等等同于
compare(A.left, B.left) && compare(A.right, B.right) || compare(A.left, B.right) && compare(A.right, B.left)
实现程序如下:
int CompTree(TreeNode* tree1,TreeNode* tree2) { if(tree1 == NULL && tree2 == NULL) return 1; if(tree1 != NULL && tree2 != NULL) { if(tree1->c == tree2->c) { if(CompTree(tree1->leftchild, tree2->leftchild) && CompTree(tree1->rightchild, tree2->rightchild) || CompTree(tree1->rightchild, tree2->leftchild) && CompTree(tree1->leftchild, tree2->rightchild)) { return 1; } } } return 0; }
相关文章推荐
- Same Tree 判断两棵树是否相等
- 判断两棵树是否相等 leecode
- java实现二叉树查找,统计结点个数,统计树的深度及判断两棵树是否相等
- (树)判断两棵树是否相等
- 百度面试题:判断两棵树是否相等
- 代码实现判断两棵树是否相等
- 二叉树(二) 求二叉树高度,根据先序和中序构建二叉树,判断二叉树是否是完全二叉树,判断两棵树是否相等
- 树---判断两棵树是否相等
- 判断两棵树是否相等
- 判断两棵树是否相等
- 用递归方法判断两棵树是否相等
- 判断两棵树是否相等
- 判断两棵树是否相等
- 判断两棵树是否相等
- java 判断两个list是否相等
- 遍历select下拉框判断其中值是否与指定值相等
- 判断两个数组是否相等
- 如和判断两个浮点数是否相等
- java中判断两个字符串是否相等的问题
- JS判断两个对象相同属性的属性值是否相等