leetcode: 113. Path Sum II

版权声明:转载请注明出处 https://blog.csdn.net/JNingWei/article/details/83817470

Difficulty

Medium.

Problem

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

Note: A leaf is a node with no children.

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

AC

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


class Solution():
    def pathSum(self, root, sum):
        if not root:
            return []
        res = []
        self.dfs(res, root, sum, [])
        return res
    def dfs(self, res, root, diff, path):
        if not root:
            return
        if not root.left and not root.right:
            if root.val == diff:
                res.append(path+[root.val])
        else:
            self.dfs(res, root.left, diff-root.val, path+[root.val])
            self.dfs(res, root.right, diff-root.val, path+[root.val])

猜你喜欢

转载自blog.csdn.net/JNingWei/article/details/83817470
今日推荐