LeetCode | 0113. Path Sum II路徑總和 II【Python】

LeetCode 0113. Path Sum II路徑總和 II【Medium】【Python】【回溯】

Problem

LeetCode

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

問題

力扣

給定一個二叉樹和一個目標和,找到所有從根節點到葉子節點路徑總和等於給定目標和的路徑。

說明: 葉子節點是指沒有子節點的節點。

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

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \    / \
    7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

思路

回溯

先序遍歷二叉樹,記錄路徑。
符合條件的加入 res 中。
回溯記得要刪除當前節點。

時間複雜度: O(n),n 爲二叉樹節點個數。
空間複雜度: O(n),最壞情況,二叉樹退化成單鏈表。

Python3代碼
# 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 recur(root, target):
            if not root:
                return
            
            path.append(root.val)
            target -= root.val
            # 找到路徑
            if target == 0 and not root.left and not root.right:
                res.append(list(path))  # 複製了一個 path 加入到 res 中,這樣修改 path 不影響 res
            recur(root.left, target)
            recur(root.right, target)
            # 向上回溯,需要刪除當前節點
            path.pop()
        
        recur(root, sum)
        return res

GitHub鏈接

Python

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