我正在编写一个简单的程序来创建带有节点的二叉树。我的代码没有问题,我只是想知道是否可以将我的代码缩短为简洁美观的
目前,我有:
//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
语句。你有什么建议吗?
答案 0 :(得分:2)
这更短,并且可能更容易阅读:
No tests found
In /Users/myuser/react/example-testing-react-enzyme-jest
19 files checked.
testMatch: /Users/myuser/react/example-testing-react-enzyme-jest/src/**/__tests__/**/*.js?(x),/Users/myuser/react/example-testing-react-enzyme-jest/src/**/?(*.)(spec|test).js?(x) - 4 matches
testPathIgnorePatterns: /node_modules/ - 19 matches
Pattern: /testing/Car_testing.test.js/ - 0 matches
Active Filters: filename /testing/Car_testing.test.js/
› Press c to clear filters.
答案 1 :(得分:1)
如何?
if (!(!root->left == !compare->left
&& !root->right == !compare->right))
return false;
通常的想法是,您可以比较两个比较的结果:
(root->left == nullptr) != (compare->left == nullptr)
答案 2 :(得分:0)
我没有在代码上方得到注释。它仅检查一个指针是否唯一为空,但不检查它们是否实际上相同。那呢:
if (root->left != compare->left || root->right != compare->right) {
return false;
}