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
  • 相关阅读:
    使用JAVA API 解析ORC File
    spark Graph 的PregelAPI 理解和使用
    流程图引擎
    JMX
    Spring走向注解驱动编程
    java@ 注解原理与使用
    Maven打包SpringBoot
    Java根据实体快速生成对象
    VBA基础出发
    “嗝嗝老师”
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546785.html
Copyright © 2011-2022 走看看