Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Maximum Root to Leaf Path Sum

Medium Acceptance 72.15% Points 30.00

You are given the root of a binary tree. Your task is to find the maximum path sum among all root-to-leaf paths.

A root-to-leaf path sum is the sum of all node values encountered while traversing from the root node to a leaf node.

Return the largest possible sum among all such paths.

Examples
Example 1

image Input: root = [1,2,3]
Output: 4
Explanation: The two root-to-leaf paths are 1 → 2 (sum = 3) and 1 → 3 (sum = 4). The maximum is 4.

Example 2

image Input: root = [10,5,15,null,null,6,null,null,7]
Output: 32
Explanation: Evaluating every root-to-leaf path, the largest total is 10 → 15 → 7 = 32.

Example 3

image Input: root = [-5]
Output: -5
Explanation: The only path consists of the single root node, so the maximum sum is -5.

Constraints
    • 1 = Number of nodes = 104
    • -10? = Node.data = 10?
Companies
Coinbase Mastercard Media.net
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