【題目描述】
輸入一顆二叉樹的跟節(jié)點和一個整數(shù),打印出二叉樹中結點值的和為輸入整數(shù)的所有路徑署拟。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中推穷,數(shù)組長度大的數(shù)組靠前)
Python坑系列:可變對象與不可變對象
【題目思路】
image.png
從根節(jié)點依次到葉節(jié)點,如果和為目標和則加入path馒铃,不是則回退。
代碼:
# self.right = None
class Solution:
# 返回二維列表区宇,內部每個列表表示找到的路徑
def FindPath(self, root, expectNumber):
# write code here
def find(root, expectNumber, all_path, path, curNumber):
path.append(root.val)
curNumber = curNumber + root.val
if root.left == None and root.right==None and curNumber == expectNumber:
all_path.append(path[:])#坑,python的可變變量引用
if root.left !=None:
find(root.left, expectNumber, all_path, path, curNumber)
if root.right !=None:
find(root.right, expectNumber, all_path, path, curNumber)
path.pop()
if root==None:
return []
all_path = []
path = []
curNumber = 0
find(root, expectNumber, all_path, path, curNumber)
return all_path