Skip to main content

Binary Tree Maximum Path Sum

Return the maximum path sum of any non-empty path Example: [1,2,3] => 6

Given the root of a non-empty binary tree with integer node values, return the largest sum of values along any non-empty path. A path follows edges between adjacent nodes, uses each node at most once, and need not pass through the root. A single node is a valid path, so the result may be negative. For example, the tree [1,2,3] has a maximum path sum of 6.

Examples

You write

max_path_sum(root: Optional[TreeNode])

  1. Example 1

    Input
    [1,2,3]
    returns
    6
  2. Example 2

    Input
    [-10,9,20,null,null,15,7]
    returns
    42

The pattern behind it

Trees

I reach for it when

  • Each node has children, and the answer depends on the subtrees.
  • The statement says depth, height, ancestor or path.

Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.

All 22 Trees problems

Dynamic Programming

I reach for it when

  • Brute force repeats the same subproblem.
  • You are asked for a count, a minimum or a maximum.

Say this before you type. Say the state in one sentence, then say which smaller states it reads from.

All 37 Dynamic Programming problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Binary Tree Maximum Path Sumhard

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.