我已经写出了this leetcode问题的基本解决方案。
对于失败的测试用例([]),“运行代码”产生正确的结果([]);但是,“提交”会产生不正确的结果([“ 1-> 2-> 5”,“ 1-> 3”])。
'Submit'产生的输出与原始测试用例相同...但是,我不确定为什么会发生这种情况,因为输入明显不同。
任何提示都值得赞赏。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
global paths
paths = [ ]
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if (root):
curr_path = str(root.val)
self.binaryTreePathsHelper(root.left, curr_path)
self.binaryTreePathsHelper(root.right, curr_path)
return paths
def binaryTreePathsHelper(self, node, path):
# so the leaf (base case) has no children
# base case
if (node):
path = path + "->" + str(node.val)
if (not node.left and not node.right):
paths.append(path)
else:
# append curr_node
# & recursively call
self.binaryTreePathsHelper(node.left, path)
self.binaryTreePathsHelper(node.right, path)
答案 0 :(得分:0)
paths
在解决方案类级别定义为全局。因此,如果重用一个Solution对象,或者即使创建了多个Solution对象,也将其初始化为一个空列表,并且不会重新初始化。因此,一旦生成非空结果,它将在paths
中徘徊,从而污染以后的结果。最好将paths
设置为实例属性,然后使用binaryTreePaths
方法对其进行初始化。