【发布时间】:2020-08-04 21:33:15
【问题描述】:
我目前正在为左子右兄弟类重载相等运算符,并且该函数应该检查两棵树是否具有相同的根、相同的孩子和相同的同胞(或者总体而言,如果两棵树恰好是一样)
bool CTree::operator==(const CTree &root){
if(this->kids!=nullptr){
return ((kids)==(root.kids));
}
else{
if(this->sibs!=nullptr){
return ((sibs)==(root.sibs));
}
else{
return (data==root.data);
}
}
}
这是我当前检查两个左子右兄弟树是否相等的函数;我认为这有两个问题我找不到解决方法;首先,它返回kids==root.kids 而不检查sibs,其次,一旦kids 和sibs 指向null,这个函数就会停止检查两棵树的相等性。我试图写第二个函数
bool CTree::operator==(const CTree &root){
if(this->kids!=nullptr){
if (!(kids==root.kids)){
return false;
}
}
else{
if(this->sibs!=nullptr){
if (!(kids==root.sibs)){
return false;
}
}
else{
if (!(data==root.data)){
return false;
}
}
}
return true;
}
但这也不能正确检查两棵树的相等性。有人可以给我一个提示如何进行吗?我包含了部分头文件以供参考
class CTree {
friend class CTreeTest;
char data; // the value stored in the tree node
CTree * kids; // children - pointer to first child of list, maintain order & uniqueness
CTree * sibs; // siblings - pointer to rest of children list, maintain order & uniqueness
// this should always be null if the object is the root of a tree
CTree * prev; // pointer to parent if this is a first child, or left sibling otherwise
// this should always be null if the object is the root of a tree}
【问题讨论】:
-
如果我们能看到 CTree 标题会更容易判断
-
@Jeffrey 对不起,我忘了包括它!感谢您指出这一点!
-
什么是 CTree?我以前从未听说过这种数据结构。根据描述,我无法理解
kids和sibs之间的区别。 -
你的结构对我来说没有意义。一个人怎么知道有多少孩子?同胞也有同样的问题。
-
不知道你最后比较
data == root.data。我会先做这个比较,以尽早终止递归。如果节点本身不相等,则检查节点的所有子节点(成对)是没有意义的,不是吗?
标签: c++ class recursion tree operator-overloading