二叉树 hasPathSum() 实现
你好 我正在尝试实现 hasPathSum()
对于给定的数字意味着根节点到叶节点之间是否存在任何路径。
我从斯坦福网站获得了这段代码。我认为这是错误的
/**
Given a tree and a sum, returns true if there is a path from the root
down to a leaf, such that adding up all the values along the path
equals the given sum.
Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*/
boolean hasPathSum(Node node, int sum) {
// return true if we run out of tree and sum==0
if (node == null){
return(sum == 0);
}
else {
// otherwise check both subtrees
int subSum = sum - node.data;
return(hasPathSum(node.left, subSum) || hasPathSum(node.right, subSum));
}
这是正确的实施吗?
我认为这个 if 应该是
- if(node.left==null && node.right==null)
如果我错了,请清除我的困惑,
考虑一下案例:
5
/ \
2 1
/
3
-谢谢
Hi
I am trying to implement hasPathSum()
means for given number is there any path exist between root-to-leaf node.
I got this code from Stanford website. And i am thinking this is wrong
/**
Given a tree and a sum, returns true if there is a path from the root
down to a leaf, such that adding up all the values along the path
equals the given sum.
Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*/
boolean hasPathSum(Node node, int sum) {
// return true if we run out of tree and sum==0
if (node == null){
return(sum == 0);
}
else {
// otherwise check both subtrees
int subSum = sum - node.data;
return(hasPathSum(node.left, subSum) || hasPathSum(node.right, subSum));
}
Is this a right implementation?
I am thinking this if should be
- if(node.left==null && node.right==null)
If i am wrong Please clear my confusion
consider this case:
5
/ \
2 1
/
3
-Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您确实应该编写代码并尝试一下 - 这样您可以学到很多东西。 (编辑:我当然是...)
我相信原始代码对于
hasPathSum(tree, 7)
失败,因为节点 2 不是叶子。编辑:
由于明显错误而撤回原始代码 - 至少对除了我之外的每个人来说都是显而易见的:-)
编辑:
我的新解决方案如下。请注意,所包含的优化(
if (sum <= node.data)
)假设树由所有正数据值组成。如果树的数据值为零或负,则应将其删除或调整。 (感谢@马克·彼得斯)。另请注意答案注释中有关处理
hasPathSum(null, 0)
的讨论。完整代码:
示例运行:(注意案例 7)
You really should just code it and try it - you learn a lot that way. (Edit: I certainly am ...)
I believe the original code fails for
hasPathSum(tree, 7)
because node 2 is not a leaf.Edit:
Original code withdrawn due to obvious mistakes - obvious at least to everyone but me :-)
Edit:
My new solution is below. Note that the included optimization (
if (sum <= node.data)
) assumes the tree is made up of all positive data values. It should be removed or tweaked if the tree has zero or negative data values. (thanks @Mark Peters).Also note the discussion in the answer comments about handling
hasPathSum(null, 0)
.Full code:
Sample run: (Note case 7)
由于伯特没有修正他的答案,我将发布正确的答案。
是的,你是对的,原始代码已被破坏,尽管这里大多数人都这么说。在您的示例中,
调用
尽管没有添加到 7 的根到叶路径,但 仍将返回
true
。这是因为当到达节点2
时,它会递归检查右子节点(总和为 0),然后返回 true,因为右子节点为null
。该修复的灵感来自 Bert 的回答:
如果需要,您可以将 else 块合并为一个长语句(大量的 and 和 ors),但我发现这样更干净。
Since Bert isn't fixing his answer, I'll post the correct one.
Yes, you're right that the original code is broken, despite what most people here are saying. In your example
Calling
will return
true
despite the fact that there is no root-to-leaf path that adds to 7. That's because when node2
is reached, it recursively checks the right child (with sum 0), which then returns true because the right child isnull
.The fix is inspired by Bert's answer:
You can roll the else block into one long statement if you want (lots of ands and ors), but I find this cleaner.
嗨,大家好
感谢您的回答,这个讨论看起来很有趣,
昨晚我再次尝试实现这个功能,我认为我的解决方案适用于所有情况,
实际上我以更简单的方式实现,以便每个人都可以理解
有四种情况需要检查
一个特殊的case:如果您直接将输入树作为 null 传递,则需要处理(如果块请求还需要一个。)
请查看我的代码
这适用于所有二叉树情况吗?和
如果需要任何更改,请告诉我。
-谢谢
Hi guys
Thanks for your answers, this discussion seems very intersting,
last night again i tried to implement this function and i think my solution will work for all cases,
actually I implemented in simpler way so that it can be understandable by everyone
There are four cases to check
One special case: if you pass input tree directly as null then it is required to handle (one more if block req.)
Please review my code
will this work for all the binary tree cases? and
let me know if any changes are required.
-Thanks
对于以下简单情况,OP 的函数显然会失败:
上面的树只是 sum
3
的一个根到叶路径。但是 OP 的函数将返回 true forhasPathSum(root,1)
发生这种情况是因为只有当我们到达叶节点(空左子树和空右子树)或空树的特殊情况。
OP 的功能是将任何具有
NULL
子节点的节点视为叶子。以下函数(与 Mark 的函数相同 + 一项附加检查)修复了该问题:
C 版本:Ideone Link
OP's function clearly fails for the following simple case:
The above tree as just one root to leaf path of sum
3
. But OP's function will return true forhasPathSum(root,1)
This happens because the changing sub-sum should be compared to zero only when we reach a leaf node(empty left sub-tree and empty right sub-tree) or a special case of an empty tree.
OP's function is treating any node with
NULL
child as leaf.The following function( which is same as Mark's + one additional check) fixes it:
C version: Ideone Link
这是另一种方法,它计算每条路径的总和,并将其与目标值相匹配。恕我直言,这似乎比使用子和逻辑更直观。
此外,nums 列表将存储所有根到叶路径的总和。我添加这个只是为了确保我的代码不会生成任何不需要的路径。
Here is an alternative approach that calculates the sum of each path, and matches it to the target value. IMHO, this seems more intuitive than using the logic of subsums.
Additionally, the nums list would store all root-to-leaf paths sums. I added this just to make sure that my code wasn't generating any unwanted paths.
试试这个
try this