Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Root To Leaf Path Sum

Medium Acceptance 78.56% Points 30.00

You are given the root of a binary tree and an integer targetSum. Your task is to determine whether there exists a root-to-leaf path such that the sum of the node values along the path equals targetSum.

A root-to-leaf path is a path that:

  • Starts from the root node.
  • Ends at a leaf node (a node with no children).
  • Includes every node along the path exactly once.

Return true if such a path exists; otherwise, return false.

Examples
Example 1

image Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The path 5 → 4 → 11 → 2 has a sum of 22.

Example 2

image Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: No root-to-leaf path has a sum of 5.

Example 3

image Input: root = [], targetSum = 0
Output: false
Explanation: The tree is empty, so no root-to-leaf path exists.

Constraints
    • 0 = Number of nodes = 105
    • -10? = Node.data = 10?
    • -10? = targetSum = 10?
Companies
Samsung Sprinklr Myntra
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions