34. 二叉樹中和爲某一值的路徑(中等)

題目描述:

輸入一棵二叉樹和一個整數,打印出二叉樹中節點值的和爲輸入整數的所有路徑。
從樹的根節點開始往下一直到葉節點所經過的節點形成一條路徑。

示例:
給定如下二叉樹,以及目標和 sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回:

[
   [5,4,11,2],
   [5,8,4,5]
]
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        res,path=[],[]
        def findpath(root,sum):
            if not root:
                return 
            else:
                path.append(root.val)
                sum -= root.val
                if not root.left and not root.right and not sum:    # 此時走到了葉子節點上,且sum==0
                    res.append(path[:]) #這一路徑添加進來
                findpath(root.left,sum)
                findpath(root.right,sum)
            path.pop()  #不滿足條件,回溯
        findpath(root,sum)
        return res

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章