Leetcode 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) & (not root.right):
            return root.val==sum
        elif not root.left:
            return self.hasPathSum(root.right,sum-root.val)
        elif not root.right:
            return self.hasPathSum(root.left,sum-root.val)
        else:
            return (self.hasPathSum(root.left,sum-root.val))|(self.hasPathSum(root.right,sum-root.val))

 

posted @ 2019-03-10 05:22  周洋  阅读(232)  评论(0编辑  收藏  举报