二进制树木遍历 - 递归
在下面写下了leetcode问题的解决方案 -
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode],traversal_list = []) -> List[int]:
if root:
traversal_list= self.inorderTraversal(root.left,traversal_list)
traversal_list.append(root.val)
traversal_list = self.inorderTraversal(root.right, traversal_list)
return traversal_list
从示例问题1返回[1,3,2]的正确解决方案。 示例问题2:[]再次返回[1,3,2]。
为什么答案#1被带到问题2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要修改参数的默认值
leetcode提供的模板 -
代码的问题在这里 -
traversal_list
,默认值为<代码> []traversal_list
用.append
突变reteation the问题
这意味着随后调用
解决方案#inordertraversal
将包含一个预处理的traversal_list
,并导致错误的答案。您可以在下面的问题中看到最小的娱乐 -在另一个示例中,查看如何评估默认参数值 执行脚本时 -
修复修复
修复它删除第三个参数,
traversal_list
。没有必要。只需返回[]
当不存在root
时 -编写此书的改进方法是在类外编写遍历函数 -
don't modify a parameter's default value
The template provided by LeetCode -
The problem with your code is here -
traversal_list
, with a default value of[]
traversal_list
is mutated with.append
recreation of the problem
This means subsequent calls to
Solution#inorderTraversal
will contain a prepopulatedtraversal_list
and result in an incorrect answer. You can see a minimal recreation of the problem in below -In another example, look how the default parameter value is evaluated only once when the script is executed -
fix it
To fix it, remove the third parameter,
traversal_list
. There's no need for it. Simply return[]
whenroot
is not present -An improved way to write this is to write a traversal function outside of the class -
"what if i want to use append?"
If you absolutely want to use
.append
, you can model the solution above in a similar way.not a universal behavior
Note this behaviour is in direct contrast to other languages. For example, JavaScript will re-evaluate a parameter's default value each time the function is run -