Problem · Tree
EasySalesforce logoSalesforceFULLTIMEONSITE INTERVIEW
See Salesforce hiring insights

Problem statement

Given the root of a binary tree and an integer targetSum, return true if the tree contains a root-to-leaf path whose node values add up to targetSum. Otherwise, return false.

A leaf is a node with no left child and no right child. The path must begin at the root and end at a leaf.

An empty tree has no root-to-leaf path, so it returns false for every target.

Function

hasPathSum(root: TreeNode, targetSum: int) → boolean

Examples

Example 1

root = [5,4,8,11,null,13,4,7,2,null,null,null,1]targetSum = 22return = true

The root-to-leaf path 5 → 4 → 11 → 2 has sum 22.

Example 2

root = [1,2,3]targetSum = 5return = false

The two root-to-leaf sums are 1 + 2 = 3 and 1 + 3 = 4, so neither equals 5.

Example 3

root = []targetSum = 0return = false

The tree is empty, so it has no root-to-leaf path.

Constraints

  • The tree contains at most 5000 nodes.
  • Each node value is between -1000 and 1000, inclusive.
  • -10^9 <= targetSum <= 10^9

More Salesforce problems

drafts saved locally
public boolean hasPathSum(TreeNode root, int targetSum) {
    // Write your solution here
}
root[5,4,8,11,null,13,4,7,2,null,null,null,1]
targetSum22
expectedtrue
checking account