Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
您的代码仅着眼于根部及其直接孩子。它从不看树木的子树的情况。例如,从未检查过根的孙子,当他们违反年龄要求时,您的功能仍然可以返回
true
。您需要在根以下的两个子树上调用该功能本身。如果这样的递归呼叫返回false,则可以立即将false返回给呼叫者,因为 a 违规就足以拒绝整棵树。
这不是问题,但是以下是一种反模式:
相反,您应该做:
实际上,在这种情况下,整个逻辑可以以一个布尔的表达方式表达,这可以是函数的返回值:
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:
Instead, you should just do:
In fact, in this case the whole logic can be expressed in one boolean expression, which can be the function's return value: