递归与二叉树_leetcode113

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


#coding=utf-8
# 解题思路: 递归返回值 20190305 找工作期间
# 递归返回值的处理、要定义好函数的返回逻辑或状态或者值,并从底向上构建
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""

res = []
if not root:
return res

if not root.left and not root.right:
if root.val == sum:
res.append(str(root.val))

return res

leftPaths = self.pathSum(root.left,sum - root.val)

for i in range(len(leftPaths)):

res.append(str(root.val) + "," + leftPaths[i])

rightPaths = self.pathSum(root.right,sum - root.val)

for i in range(len(rightPaths)):

res.append(str(root.val) + "," + rightPaths[i])

return res


class Solution2(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""

res = []
if not root:
return res

if not root.left and not root.right:
if root.val == sum:
res.append([root.val])

return res

leftPaths = self.pathSum(root.left,sum - root.val)

for i in range(len(leftPaths)):

res.append([root.val] + leftPaths[i])

rightPaths = self.pathSum(root.right,sum - root.val)


for i in range(len(rightPaths)):

res.append([root.val] + rightPaths[i])

return res

猜你喜欢

转载自www.cnblogs.com/lux-ace/p/10546785.html