里面总是反映我添加的是空列表,后来使用了list函数,但是不知道是什么原因,就通过了
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
result = []
temp = []
r = root
if not root:
return []
list1 = []
cur = root
num = expectNumber
if cur.val <= num:
list1.append(cur)
temp.append(cur.val)
num = num - cur.val
cur.val = -100
while len(list1):
cur = list1[-1]
if num == 0 and not cur.left and not cur.right:
result.append(list(temp))
if cur.left and cur.left.val != -100 and cur.left.val <= num:
cur = cur.left
list1.append(cur)
temp.append(cur.val)
num = num - cur.val
cur.val = -100
elif cur.right and cur.right.val != -100 and cur.right.val <= num:
cur = cur.right
list1.append(cur)
temp.append(cur.val)
num = num - cur.val
cur.val = -100
else:
num += temp[-1]
del temp[-1]
del list1[-1]
if len(list1):
cur = list1[-1]
result.sort(key = len)
result.reverse()
return result
也可以使用递归实现