码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Path Sum

时间:2017-07-30 18:06:05      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:https   view   efi   ber   pretty   man   bool   end   roo   

LeetCode解题之Path Sum


原题

推断一棵二叉树是否有一条从根节点到某一叶子节点的路径,该路径上全部节点的和为一个特定值。

注意点:

样例:

输入: sum = 12

    3
   /   9  20
    /     15   7
  /
 14

输出: True (3->9)

解题思路

直接通过递归来解决,推断一个节点时,先把要求的值先减去该节点的值,假设剩下要求的值为0且当前的节点就是一个叶子节点,那么从根节点到当前节点的路径就符合题目的要求。

否则就要继续递归当前节点的左右节点。

AC源代码

# 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 not root:
            return False
        sum -= root.val
        if sum == 0 and root.left is None and root.right is None:
            return True
        return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)


if __name__ == "__main__":
    None

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

LeetCode Path Sum

标签:https   view   efi   ber   pretty   man   bool   end   roo   

原文地址:http://www.cnblogs.com/tlnshuju/p/7259635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!