1. 程式人生 > >劍指offer——找出二叉樹和為n的路徑

劍指offer——找出二叉樹和為n的路徑

連結串列和二叉樹比較難做,主要因其均以鏈相連線,.next and .left 來輸出結構中的資料,無法精確定位,所以通常用遞迴方法實現。
通過遞迴方法,本人感覺最重要的是確定.next的這部中具體實現的操作,然後逐漸實現遞迴。找出二叉樹和為n的路徑,就針對每一步做加和操作以及記錄路徑,並判斷遞迴是否截至。
下面是拷貝程式碼, 不過思考多次仍不解,最後的list.pop與輸出list1的關係。望有心著指點本菜雞。
class Solution:
    # 返回二維列表,內部每個列表表示找到的路徑
    def __init__(self):
        self.list=[]
        self.list1=[]
    def
FindPath(self, root, expectNumber):
# write code here if not root: return self.list1 self.list.append(root.val) expectNumber-=root.val if expectNumber==0 and root.left==None and root.right==None: newlist=[] for i in self.list: newlist.append(i) self.list1.append(newlist) self.FindPath(root.left,expectNumber) self.FindPath(root.right,expectNumber) self.list.pop() return
self.list1