FunctionRacerProblemsRace

Maximum Root-to-Leaf Sum

EasyTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Among all paths from the root down to a leaf, find the one whose values add up to the most, and return that sum. Values may be negative, and a path must end at a leaf (a node with no children). An empty tree gives 0.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [10,-2,7,8,-4]
returns 17

Paths: 10-2+8 = 16, 10-2-4 = 4, 10+7 = 17. The best is 17.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems