Find Whether a Complete Root Path Has a Target Sum

Quick Overview

Test for a complete root-to-leaf value sum while handling empty trees, negative values and internal prefixes.

Find Whether a Complete Root Path Has a Target Sum

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Decide whether a binary tree contains a root-to-leaf path whose values add up to `targetSum`. Return a Boolean. The path must start at the root and end at a node with no children; stopping at an internal node is insufficient. An empty tree has no qualifying path. ```cpp bool hasPathSum(TreeNode* root, int targetSum); ``` Keep the supplied `TreeNode` pointer interface. Brackets display level-order tree structure. ### Examples ```text Input: root = [4,-2,7,3,null,-1,2], targetSum = 5 Output: true ``` The path 4→-2→3 sums to 5. ```text Input: root = [4,-2], targetSum = 4 Output: false ``` The root has a child, so its value alone is not a root-to-leaf path. ### Constraints - The tree contains between 0 and 5000 nodes. - Every node value and `targetSum` are between -1000 and 1000, inclusive.

Overview: Test for a complete root-to-leaf value sum while handling empty trees, negative values and internal prefixes.

Google logo
Google
Date not reported
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Decide whether a binary tree contains a root-to-leaf path whose values add up to targetSum. Return a Boolean. The path must start at the root and end at a node with no children; stopping at an internal node is insufficient. An empty tree has no qualifying path.

bool hasPathSum(TreeNode* root, int targetSum);

Keep the supplied TreeNode pointer interface. Brackets display level-order tree structure.

Examples

Input: root = [4,-2,7,3,null,-1,2], targetSum = 5
Output: true

The path 4→-2→3 sums to 5.

Input: root = [4,-2], targetSum = 4
Output: false

The root has a child, so its value alone is not a root-to-leaf path.

Constraints

  • The tree contains between 0 and 5000 nodes.
  • Every node value and targetSum are between -1000 and 1000, inclusive.