zoukankan      html  css  js  c++  java
  • 递归与二叉树_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
  • 相关阅读:
    python中的编码问题
    CVPR2018 Tutorial 之 Visual Recognition and Beyond
    hdu 1376 Octal Fractions
    hdu 1329 Hanoi Tower Troubles Again!
    hdu 1309 Loansome Car Buyer
    hdu 1333 Smith Numbers
    hdu 1288 Hat's Tea
    hdu 1284 钱币兑换问题
    hdu 1275 两车追及或相遇问题
    hdu 1270 小希的数表
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546785.html
Copyright © 2011-2022 走看看