Hone logo
Hone
Problems

Binary Tree Maximum Path Sum

Given the root of a binary tree, find the maximum sum of a path in the tree. A path can be any sequence of nodes along a single branch or a series of connected nodes. This problem is a classic tree traversal challenge, useful for understanding recursion and dynamic programming approaches to tree problems.

Problem Description

You are given the root node of a binary tree. Each node in the tree has a value (an integer). Your task is to determine the maximum sum of values along any path from any node in the tree to any other node. A path can consist of just a single node. The path does not necessarily need to pass through the root.

What needs to be achieved:

  • Traverse the binary tree.
  • Calculate the maximum path sum.
  • Return the maximum path sum found.

Key Requirements:

  • The path can start and end at any node in the tree.
  • The path can be a single node (in which case the path sum is just the node's value).
  • The path can go up, down, or sideways in the tree.
  • The path cannot loop back on itself.

Expected Behavior:

The function should return an integer representing the maximum path sum.

Edge Cases to Consider:

  • Empty tree (root is null): Return 0.
  • Tree with only one node: Return the node's value.
  • Tree with negative node values: The maximum path sum might be negative.
  • Tree with a mix of positive and negative node values.

Examples

Example 1:

Input: root = [1,2,3]
       1
      / \
     2   3
Output: 6
Explanation: The maximum path sum is 1 + 2 + 3 = 6.

Example 2:

Input: root = [-10,9,20,15,7]
       -10
        / \
       9  20
         /  \
        15   7
Output: 42
Explanation: The maximum path sum is 9 + 20 + 15 + 7 = 42.

Example 3:

Input: root = [-1]
Output: -1
Explanation: The maximum path sum is -1 (the single node).

Constraints

  • The tree has between 1 and 10^5 nodes.
  • The value of each node is between -1000 and 1000.
  • The solution should have a time complexity of O(N), where N is the number of nodes in the tree. A recursive solution is acceptable.

Notes

Consider using a recursive approach. During the recursion, you can maintain a running sum and update the global maximum path sum as you traverse the tree. Think about how to handle negative node values – they might reduce the path sum, but they could also be part of the optimal path. The key is to consider the maximum path sum ending at each node. This can be used to calculate the overall maximum path sum. You don't need to return the actual path, just the sum.

Loading editor...
plaintext