检查两个节点在子节点上是否具有相同状态的更优雅的方法



我正在编写一个简单的程序来创建带有节点的二叉树。我对代码没有问题,我只是想知道是否可以将我的代码缩短为优雅美观的东西

目前我有:

//helper function for overloaded ==
//checks to see if both nodes in Binary Trees have the same children nodes
//filled. If not, due to preconditions, they would not be equal
if ((root->left == nullptr && compare->left != nullptr)
|| (root->left != nullptr && compare->left == nullptr)
|| (root->right == nullptr && compare->right != nullptr)
|| (root->right != nullptr && compare->right == nullptr)) 
{
return false;
}

我能想到的唯一其他方法是将其分解为多个if语句。你有什么建议吗?

这更短,可能更易于阅读:

if ((root->left == nullptr) != (compare->left == nullptr)
|| (root->right == nullptr) != (compare->right == nullptr))
{
return false
}

这个怎么样:

if (!(!root->left == !compare->left
&& !root->right == !compare->right))
return false;

一般的想法是,您可以比较两个比较的结果:

(root->left == nullptr) != (compare->left == nullptr)

我在代码上方没有得到注释。它只检查一个指针是否完全为 null,但不检查它们是否实际上相同。这个呢:

if (root->left != compare->left || root->right != compare->right) {
return false;
}

最新更新