1. 程式人生 > >LeetCode 113. Path Sum II 20170705 部分之前做了沒寫的題目

LeetCode 113. Path Sum II 20170705 部分之前做了沒寫的題目

for list 路徑 父節點 leetcode pathsum and left -1

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非常相似,只不過上一題只需判斷是否存在符合條件的路徑,而該題需要將符合條件的路徑輸出,難度加大了。解題的思路是,像上一題一樣遍歷整棵樹,每走一步,就先用sum減掉父節點的值,然後這裏要多做一步就是把父節點的值加入到當前路徑中。最後到了葉子節點的時候,判斷當前sum是否等於葉子節點的值,如果相等的話,說明該條路徑是符合要求的路徑,把葉子節點的值也加入當前路徑中然後輸出。

技術分享

class Solution(object):
  def pathSum(self, root, sum):
    """
    :type root: TreeNode
    :type sum: int
    :rtype: List[List[int]]
    """
    A=[]
    def haspathSum(root, sum, path):
      if root == None:
        return A
      if sum == root.val and root.left == None and root.right == None:
        return A + [path + [root.val]]
      else:
        return haspathSum(root.left, sum - root.val, path + [root.val]) + haspathSum(root.right, sum - root.val, path + [root.val])
    return haspathSum(root, sum, [])

LeetCode 113. Path Sum II 20170705 部分之前做了沒寫的題目