zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):112-Path Sum

    题目来源:

      https://leetcode.com/problems/path-sum/


    题意分析:

      给出一个树和一个整数,判断这棵树是否有一条从根到叶节点的路径,使得路径之和为给定的整数。


    题目思路:

      这题还是用递归的思想。如果根节点的左右子树都为空,那么返回根的值是否等于sum,否者,sum 减去根的值得到一个newsum,判断newsum在左子树或者右子树是否有路径。


    代码(python):

      

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def hasPathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: bool
            """
            if root == None:
                return False
            if root.left == None and root.right == None:
                return root.val == sum
            if root.left == None:
                return self.hasPathSum(root.right,sum - root.val)
            if root.right == None:
                return self.hasPathSum(root.left,sum - root.val)
            return self.hasPathSum(root.left,sum - root.val) or self.hasPathSum(root.right,sum - root.val)
    View Code
  • 相关阅读:
    6种基本排序(C++实现)
    关于 ^ 异或 及 无中间变量进行交换
    清理C盘旧驱动
    sqlmap基本使用
    http头部注入
    waf绕过注入
    mysql报错注入
    Burp Suite工具使用
    mysql注入
    Linux网络配置
  • 原文地址:https://www.cnblogs.com/chruny/p/5258546.html
Copyright © 2011-2022 走看看