1. 程式人生 > >劍指offer-二叉樹中和為某一值的路徑python

劍指offer-二叉樹中和為某一值的路徑python

相當於深度搜索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]]

你的輸出為:

[[],[]]