[LeetCode]题解(python):113-Path Sum II

题目来源:

  https://leetcode.com/problems/path-sum-ii/


题意分析:

  给出一个二叉树和一个整数,返回所有从根节点到叶节点的和等于这个整数的路径。


题目思路:

  这题和上一题类似,直接深度递归。记录左子树和sum - 根的值的答案,以及右子树和sum- 根的值的答案。


代码(python):

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        if root == None:
            return []
        ans = []
        if root.left == None and root.right == None:
            if root.val == sum:
                return [[sum]]
            else:
                return []
        l,r = self.pathSum(root.left,sum - root.val),self.pathSum(root.right,sum - root.val)
        for i in l:
            ans.append([root.val] + i)
        for i in r:
            ans.append([root.val] + i)
        return ans
View Code
原文地址:https://www.cnblogs.com/chruny/p/5258576.html