//运算符==重载函数
template<class ElemType>
bool BinaryTree<ElemType>::operator ==(const BinaryTree<ElemType> &T) {
if(checkEqual(root,T.GetRoot())==true)
return true;
else
return false;
}
template<class ElemType>
bool BinaryTree<ElemType>::checkEqual(const BinaryTreeNode<ElemType> *root1, const BinaryTreeNode<ElemType> *root2) {
if(root1&&root2) {
if(root1->Getdata()==root2->Getdata()) {
return checkEqual(root1->GetLChild(),root2->GetLChild())&&checkEqual(root1->GetRChild(),root2->GetRChild());//这步,重要!!!
} else
return false;
} else if((!root1&&root2)||(root1&&!root2))
return false;
else
return true;
}
判断两个树是否相同,重要的一点是当两个树都为空的时候,返回的是true,当两棵树都非空时才进行左右子树的判断,相同为true,不同返回false,其余情况都返回false;
另外,因为函数本身就是bool类型的,所以可以直接用来判断并返回,不需要if语句;