xqn2017

导航

112. Path Sum

原文题目:

112. Path Sum

读题:

二叉树中是否存在给定和为给定数的路径,递归实现最简单

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

  

posted on 2017-12-08 19:14  xqn2017  阅读(107)  评论(0编辑  收藏  举报