VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-maximum-path-sum-in-a-binary-tree/

⇱ Maximum Path Sum in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Path Sum in a Binary Tree

Last Updated : 7 Oct, 2025

Given the root of the binary tree, Find the maximum path sum. The path may start and end at any node in the tree.

Example: 

Input: 

πŸ‘ tree_2

Output: 42
Explanation: Max path sum is represented using green color nodes in the above binary tree.

πŸ‘ 420046695

Input:

πŸ‘ 420046696

Output: 31
Explanation: Max path sum is represented using green color nodes in the above binary tree.

πŸ‘ 420046696

[Approach] Using Recursion - O(n) Time and O(h) Recursive Space

The idea is to use postorder traversal. At each node, calculate left and right path sums, and update a global maximum with (left + node + right). Return the node’s value plus the larger side upward. The global maximum at the end gives the answer.

Why this works:
Any maximum path in a binary tree must pass through some "highest" node (its root in that path). By considering every node as a possible highest point and updating the maximum with left + node + right, we guarantee that the best path is captured. Returning only one side ensures valid extension toward the parent without breaking the path structure.


Output
42
Comment
Article Tags:
Article Tags: