Question: https://oj.leetcode.com/problems/path-sum/
Question Name: Path Sum
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @param sum, an integer # @return a boolean def hasPathSum(self, root, sum): if root == None: # Empty tree will always result in False return False elif root.left == None and root.right == None: # Reach the leaf. return root.val == sum elif root.left == None: # Only has right child. return self.hasPathSum(root.right, sum-root.val) elif root.right == None: # Only has left child. return self.hasPathSum(root.left, sum-root.val) else: # Has two children. return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val) |