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
  • 相关阅读:
    把Linux安装到移动硬盘上
    关于thinkphp 开发的网站部署问题
    lamp 网站打不开,不显示也不报错,
    前端之css语法3
    前端之css笔记2
    前端之练习2
    前端之css笔记1
    前端之笔记1
    前端之练习1
    MySQL之练习题5
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3752503.html
Copyright © 2011-2022 走看看