相当于深度搜索dfs
class Solution:
def dfs(self,root,s,li,listAll):
li.append(root.val)
if not root.left and not root.right and s==root.val:
listAll.append(li)
if root.left:
self.dfs(root.left,s-root.val,li,listAll)
if root.right:
self.dfs(root.right,s-root.val,li,listAll)
li.pop()
def FindPath(self, root, expectNumber):
li = []
listAll = []
if root:
self.dfs(root,expectNumber,li,listAll)
return listAll
class Solution:
def __init__(self):
self.li = []
self.liAll = []
def FindPath(self, root, expectNumber):
# write code here
if root is None:
return self.liAll
self.li.append(root.val)
expectNumber -= root.val
if expectNumber==0 and not root.left and not root.right:
self.liAll.append(self.li[:])
self.FindPath(root.left,expectNumber)
self.FindPath(root.right,expectNumber)
self.li.pop()
return self.liAll
注意把一个列表加到另一个列表中作为另一个列表的元素,一定要这样写list2.append(list1[:]),不然会加的是空的,错误学习地址https://www.cnblogs.com/bitpeng/p/4748148.html
您的代码已保存
答案错误:您提交的程序没有通过所有的测试用例
case通过率为0.00%
测试用例:
{10,5,12,4,7},22
对应输出应该为:
[[10,5,7],[10,12]]
你的输出为:
[[],[]]