Problem · Tree

Binary Tree Maximum Path Sum

Learn this problem
HardArcesium logoArcesiumINTERNOA

Problem statement

You are given a non-empty binary tree encoded by the integer array levelOrder.

The array lists nodes in breadth-first order. The value -1001 marks a missing child; every other value is a tree node. Children are consumed from left to right only for non-missing nodes.

A path is a sequence of nodes in which each adjacent pair is connected by an edge. A node may appear at most once, and the path does not need to pass through the root.

Return the maximum sum of node values along any non-empty path.

Function

maxPathSum(levelOrder: int[]) → int

Examples

Example 1

levelOrder = [-10,9,20,-1001,-1001,15,7]return = 42

The best path is 15 -> 20 -> 7, whose sum is 42.

Example 2

levelOrder = [1,2,3]return = 6

The path 2 -> 1 -> 3 contains all three nodes and sums to 6.

Example 3

levelOrder = [-3]return = -3

A path must be non-empty, so the single node gives the maximum sum -3.

Constraints

  • The tree contains between 1 and 3 * 10^4 non-missing nodes.
  • Every node value is in the range [-1000, 1000].
  • levelOrder[0] != -1001.
  • levelOrder is a valid compact breadth-first encoding, and -1001 appears only as the missing-child marker.

More Arcesium problems

drafts saved locally
public int maxPathSum(int[] levelOrder) {
  // Write your code here.
}
levelOrder[-10,9,20,-1001,-1001,15,7]
expected42
checking account