这篇文章是程序自动发表的,详情可以见
这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这是leetcode的第113题--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] ]
思路 分四种情况讨论即可
show me the code
# 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, sm): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ if not root:return [] paths = self.getPath(root) print paths return [i for i in paths if sum(i) == sm] def getPath(self,root): if not root.left and not root.right: return [[root.val]] li = [] if root.left : li =self.getPath(root.left) if root.right : li =self.getPath(root.right) for i in li: i.insert(0,root.val) return li