Binary Tree Maximum Path Sum

HardTreestree dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

In a binary tree, a **path** is a sequence of nodes where each consecutive pair is joined by an edge, and no node appears more than once. A path has at least one node, does not have to pass through the root, and may turn at most once (going up to some node and then down another branch). Given the root of a non-empty binary tree, return the largest possible sum of node values along any path. Values can be negative, so the best path may be a single node. Aim for O(n) time with one post-order traversal.

Examples

Input: root = [1,2,3]
Output: 6
The path 2 -> 1 -> 3 sums to 6.
Input: root = [-10,9,20,null,null,15,7]
Output: 42
The path 15 -> 20 -> 7 sums to 42; including -10 would only lower it.
Input: root = [-3,-1,-2]
Output: -1
Every value is negative, so the best path is the single node -1.

Constraints

  • 1 <= number of nodes <= 3 * 10^4
  • -1000 <= Node.val <= 1000
  • The answer fits in a signed 32-bit integer

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More tree dp problems