LeetCode | 面試題34. 二叉樹中和爲某一值的路徑【劍指Offer】【Python】

LeetCode 面試題34. 二叉樹中和爲某一值的路徑【劍指Offer】【Medium】【Python】【回溯】

問題

力扣

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

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

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

返回:

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

提示:

  1. 節點總數 <= 10000

注意:本題與主站 113 題 相同。

思路

回溯

先序遍歷二叉樹,記錄路徑。
符合條件的加入 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

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