参考了csdn中的代码https://blog.csdn.net/u010005281/article/details/79623396
注意把一个列表加到另一个列表中作为另一个列表的元素,一定要这样写list2.append(list1[:]),不然加的是空的,这涉及到Python的可变对象、不可变对象等机制
class Solution: def __init__(self): self.onePath = [] self.PathArray = [] def FindPath(self, root, expectNumber): if root is None: return self.PathArray self.onePath.append(root.val) expectNumber -= root.val if expectNumber==0 and not root.left and not root.right: self.PathArray.append(self.onePath[:]) elif expectNumber>0: self.FindPath(root.left,expectNumber) self.FindPath(root.right,expectNumber) self.onePath.pop() return self.PathArray
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # -*- coding:utf-8 -*- class Solution: # 返回二维列表,内部每个列表表示找到的路径 def FindPath(self, root, expectNumber): # write code here if not root: return [] ret = [] path = [] self.Find(root, expectNumber, ret, path) # print ret # a = [];self.f(a);print a return ret def Find(self, root, target, ret, path): if not root: return path.append(root.val) isleaf = (root.left is None and root.right is None) if isleaf and target == root.val: ret.append(path[:]) if root.left: self.Find(root.left, target-root.val, ret, path) if root.right: self.Find(root.right, target-root.val, ret, path) path.pop()