0
Leetcode Problem 124. Binary Tree Maximum Path Sum
124. Binary Tree Maximum Path Sum
AI Mock Interview
Leetcode Solutions
Post Order DFS for Maximum Path Sum in Binary Tree
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Initialize a global variable
max_sum
to negative infinity.
Define a recursive function
max_gain(node)
that:
Returns 0 if
node
is null (base case).
Recursively calls itself for the left and right children of
node
.
Calculates the gain from the left and right subtrees, ignoring negative gains.
Updates
max_sum
with the maximum of
max_sum
and the sum of the node's value and gains from both subtrees.
Returns the node's value plus the maximum gain from either the left or right subtree.
Call
max_gain(root)
to start the recursion.
Return the value of
max_sum
.
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...