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
  • 相关阅读:
    TinyOS在ubuntu 14.04下安装教程
    C++ STL标准入门
    C++ 模板
    多态
    C++继承
    C++类型转换 -- 由其他类型转换到自定义类型
    运算符重载
    友元
    typedef用法
    c++细节--section1
  • 原文地址:https://www.cnblogs.com/chruny/p/5258546.html
Copyright © 2011-2022 走看看