54. Leetcode 113. 路径总和 II (二叉树-二叉树路径和)
生活随笔
收集整理的這篇文章主要介紹了
54. Leetcode 113. 路径总和 II (二叉树-二叉树路径和)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你二叉樹的根節點 root 和一個整數目標和 targetSum ,找出所有 從根節點到葉子節點 路徑總和等于給定目標和的路徑。葉子節點 是指沒有子節點的節點。示例 1:
輸入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
輸出:[[5,4,11,2],[5,8,4,5]]示例 2:
輸入:root = [1,2,3], targetSum = 5
輸出:[]示例 3:
輸入:root = [1,2], targetSum = 0
輸出:[]# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:# 方法一 遞歸def helper(root, sum, temp):if root == None:return Noneif root.left == None and root.right == None and root.val == sum:temp += [root.val]res.append(temp)helper(root.left, sum-root.val, temp + [root.val])helper(root.right, sum-root.val, temp + [root.val])res = []helper(root, targetSum, [])return res# 方法二if root == None:return []res = []temp = []stack = [(root, targetSum, temp)]while stack:node, sum, temp = stack.pop()if node.left == None and node.right == None and node.val == sum:temp += [node.val]res.append(temp)if node.left:stack.append((node.left, sum-node.val, temp + [node.val]))if node.right:stack.append((node.right, sum-node.val, temp + [node.val]))return res
總結
以上是生活随笔為你收集整理的54. Leetcode 113. 路径总和 II (二叉树-二叉树路径和)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 53. Leetcode 112. 路径
- 下一篇: 57. Leetcode 257. 二叉