zoukankan      html  css  js  c++  java
  • [leetcode]Path Sum II @ Python

    原题地址:https://oj.leetcode.com/problems/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]
    ]

    解题思路:这题需要将根到叶子的路径和为sum的路径都枚举出来。一样是使用递归。

    代码:

    # 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
  • 相关阅读:
    C#函数参数前的修饰符
    C#正则表达式简单案例解析
    C#正则表达式
    C#反射Reflection
    C#事件
    C#委托的使用
    无法解析主机报错
    SparkStreaming对接rabbitMQ
    load文件到hive,并保存
    kafka模式对比
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3752503.html
Copyright © 2011-2022 走看看