Path Sum II
Share
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
input:[5,4,8,11,null,13,4,7,2,null,null,5,1] 22
output:[[5,4,11,2],[5,8,4,5]]
Solution
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a list of lists of integers
def pathSum(self, root, sum):
def dfs(root, currsum, valuelist):
if root.left==None and root.right==None:
if currsum==sum: res.append(valuelist)
if root.left:
dfs(root.left, currsum+root.left.val, valuelist+[root.left.val])
if root.right:
dfs(root.right, currsum+root.right.val, valuelist+[root.right.val])
res=[]
if root==None: return []
dfs(root, root.val, [root.val])
return res
遇到一个很奇怪的问题,我用上一篇博客同样的方法去dfs,list列表居然不回溯,贴在这里,以后来看
# 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]]
"""
self.num_list = []
self.generate(root, [], sum, 0)
return self.num_list
def generate(self, root, temp, sum, count):
if not root:
return
temp.append(root.val)
if not root.left and not root.right:
self.num_list.append(temp)
return
if root.left:
self.generate(root.left, temp, sum, count+root.val)
if root.right:
self.generate(root.right, temp, sum, count+root.val)