百度试题讲解:两棵树是否相等的比较

本文提供了一种用于判断两棵二叉树是否相等的算法,并附带了未经测试的C++代码示例。该算法能判断两棵树在根节点相同的情况下,其左右子树是否相等或通过左右子树互换来达到相等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

请实现两棵树是否相等的比较,相等返回,否则返回其他值,并说明算法复杂度。
数据结构为:
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
如果用你的算法也会被判断为正确。你的代码帮两种情况混在一起考虑的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值