Path Sum
Updated
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) → booleanExamples
Example 1
root = [5,4,8,11,null,13,4,7,2,null,null,null,1]targetSum = 22return = trueThe root-to-leaf path 5 → 4 → 11 → 2 has sum 22.
Example 2
root = [1,2,3]targetSum = 5return = falseThe two root-to-leaf sums are 1 + 2 = 3 and 1 + 3 = 4, so neither equals 5.
Example 3
root = []targetSum = 0return = falseThe tree is empty, so it has no root-to-leaf path.
Constraints
- The tree contains at most
5000nodes. - Each node value is between
-1000and1000, inclusive. -10^9 <= targetSum <= 10^9
More Salesforce Onsite Interview questions
- Count Increasing TripletsONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Reverse a Sublist of a Linked ListONSITE INTERVIEW · Seen Nov 2026
- Rotting OrangesONSITE INTERVIEW · Seen Nov 2026
- 3Sum SmallerONSITE INTERVIEW · Seen Nov 2026
- Count Zero Request ServersONSITE INTERVIEW · Seen Nov 2026
- Group Identical Tree LevelsONSITE INTERVIEW · Seen Oct 2026
- Meeting Rooms IIONSITE INTERVIEW · Seen Oct 2026
- Construct a Tree from Level-Order and Inorder TraversalsONSITE INTERVIEW · Seen Sep 2026
- Maximize Monsters DefeatedONSITE INTERVIEW · Seen Sep 2026
Similar questions at other companies
- Diameter of Binary TreeeBay · ONSITE INTERVIEWeBay interview questions
- Count One-Valued Regions in a Binary TreeGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Maximum Depth of Binary TreeLinkedIn · PHONE SCREEN · ONSITE INTERVIEWLinkedIn interview questions
- Binary Tree Preorder TraversalAnduril · ONSITE INTERVIEWAnduril interview questions
- Root-to-Node Path in a Binary TreeAmazon · ONSITE INTERVIEW
- Symmetric Binary TreeFigma · ONSITE INTERVIEWFigma interview questions
- Tree Level with the Most NodesBloomberg LP · ONSITE INTERVIEWBloomberg LP interview questions
- Diameter of a Binary TreeMeta · ONSITE INTERVIEWMeta interview questions
- Check That Every Node Equals Its Descendant SumMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Mirror Image Binary TreesExpedia · ONSITE INTERVIEWExpedia interview questions