Skip to content

112. Path Sum

https://leetcode.com/problems/path-sum/

js
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} sum
 * @return {boolean}
 */
function hasPathSum(root, sum) {
  if (!root) {
    return false
  }

  if (root.left && root.right) {
    return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val)
  }

  if (root.left) {
    return hasPathSum(root.left, sum - root.val)
  }

  if (root.right) {
    return hasPathSum(root.right, sum - root.val)
  }

  return root.val === sum
}
py
# 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 root.left and root.right:
            return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
        if root.left:
            return self.hasPathSum(root.left, sum - root.val)
        if root.right:
            return self.hasPathSum(root.right, sum - root.val)
        return root.val == sum
go
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func hasPathSum(root *TreeNode, sum int) bool {
	if root == nil {
		return false
	}

	if root.Left != nil && root.Right != nil {
		return hasPathSum(root.Left, sum-root.Val) || hasPathSum(root.Right, sum-root.Val)
	}

	if root.Left != nil {
		return hasPathSum(root.Left, sum-root.Val)
	}

	if root.Right != nil {
		return hasPathSum(root.Right, sum-root.Val)
	}

	return root.Val == sum
}