跳到主要内容

Path Sum II

描述

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

分析

跟上一题相比,本题是求路径本身。且要求出所有结果,左子树求到了满意结果,不能 return,要接着求右子树。

代码

# Path Sum II
# 时间复杂度O(n),空间复杂度O(logn)
class Solution:
def pathSum(self, root, sum):
result = []
cur = [] # 中间结果
self._pathSum(root, sum, cur, result)
return result

def _pathSum(self, root, gap, cur, result):
if not root:
return

cur.append(root.val)

if not root.left and not root.right: # leaf
if gap == root.val:
result.append(cur[:])

self._pathSum(root.left, gap - root.val, cur, result)
self._pathSum(root.right, gap - root.val, cur, result)

cur.pop()

相关题目