为什么此二进制代码失败了某些测试用例?

发布于 2025-02-11 00:27:21 字数 1490 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤蝉 2025-02-18 00:27:21

您的代码仅着眼于根部及其直接孩子。它从不看树木的子树的情况。例如,从未检查过根的孙子,当他们违反年龄要求时,您的功能仍然可以返回true

您需要在根以下的两个子树上调用该功能本身。如果这样的递归呼叫返回false,则可以立即将false返回给呼叫者,因为 a 违规就足以拒绝整棵树。

这不是问题,但是以下是一种反模式:

if (condition)
    return true;
else
    return false;

相反,您应该做:

return condition;

实际上,在这种情况下,整个逻辑可以以一个布尔的表达方式表达,这可以是函数的返回值:

static boolean validFamilyTree(TreeNode root) {
    return root == null ||
        (root.left == null || 
             root.val > root.left.val && validFamilyTree(root.left)
        ) &&
        (root.right == null || 
             root.val > root.right.val && validFamilyTree(root.right)
        );
}

Your code only looks at the root and its direct children. It never looks at the situation in the sub trees of the tree. For instance, the grandchildren of the root are never inspected, and when they violate the age requirement, your function could still return true.

You'd need to call the function itself on both sub trees below the root. If such a recursive call returns false, you can immediately return false to the caller, as one violation is enough to reject the whole tree.

Not a problem, but the following is an anti pattern:

if (condition)
    return true;
else
    return false;

Instead, you should just do:

return condition;

In fact, in this case the whole logic can be expressed in one boolean expression, which can be the function's return value:

static boolean validFamilyTree(TreeNode root) {
    return root == null ||
        (root.left == null || 
             root.val > root.left.val && validFamilyTree(root.left)
        ) &&
        (root.right == null || 
             root.val > root.right.val && validFamilyTree(root.right)
        );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文