AlgoMaster Logo

Binary Tree Maximum Path Sum

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Brute Force

Intuition:

The basic idea is to traverse each node of the binary tree and determine all possible paths that can be formed with this node as part of the path. Note that a path can start and terminate at any node, however, this approach might result in revisiting nodes multiple times causing inefficiency.

Steps:

  • We define a recursive function that will explore the different possible paths in the left and right subtrees.
  • At each node, consider four possibilities:
    1. Node alone (no children).
    2. Node with its left subtree.
    3. Node with its right subtree.
    4. Node with both left and right subtree as the change in path.
  • The maximum of these four possibilities gives the maximum path sum at that node.
  • Keep track of the global maximum path sum encountered during the traversal.

Code:

2. Optimized Recursive with Global Maximum

Intuition:

To optimize, we need to ensure that we only compute each subtree path sum once per node. This can be achieved by using a helper function that returns not only the maximum path sum that can include the ancestor of the current node, but also updates a global maximum variable which tracks the most optimal path seen so far.

Steps:

  • We use a helper function maxGain that computes the maximum gain from each node.
  • Use a global variable maxSum to keep track of the maximum path sum encountered.
  • If the contribution from a subtree is negative, it is better to avoid including that subtree.
  • At each node, compute the max gain through the node which can be passed to its parent.
  • This is done by taking the maximum of 0 and the gain from the left and right subtree, adding the current node's value.

Code: