简繁EN

LeetCodeNo. 079

【LeetCode with Python】 113. Path Sum II

目錄

題目

原題頁面:https://leetcode.com/problems/path-sum-ii/
題目型別:Tree, Depth-first Search
難度評價:Medium
類似題目:(E) Path Sum, (E) Binary Tree Paths

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

For 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]
]

分析

和Path Sum差不多,不過要記錄一下所有可行解。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:

def __init__(self):
self.paths = [ ]

def doPathSum(self, root, total, sum, path):
if None == root.left and None == root.right:
path.append(root.val)
result = (sum == (total + root.val))
if True == result:
self.paths.append(path)

left= False
right = False
if None != root.left:
new_path = path[:]
new_path.append(root.val)
left = self.doPathSum(root.left, total + root.val, sum, new_path)
if None != root.right:
new_path = path[:]
new_path.append(root.val)
right = self.doPathSum(root.right, total + root.val, sum, new_path)
return left or right

# @param root, a tree node
# @param sum, an integer
# @return a list of lists of integers
def pathSum(self, root, sum):
# The same Solution object may be called more than once.
self.paths = [ ]
if None == root:
return [ ] ###
result = self.doPathSum(root, 0, sum, [ ])
return self.paths

本文地址:https://xnerv.wang/zh-tw/leetcode-path-sum-ii/