πDay 8. Maximum path sum from any node π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree.
π Example Walkthrough:
Input:
root[] = [10, 2, 10, 20, 1, N, -25, N, N, N, N, 3, 4]
Output:
42
Explanation:
The maximum path sum is represented using the green colored nodes in the binary tree.
Input:
root[] = [-17, 11, 4, 20, -2, 10]
Output:
31
Explanation:
The maximum path sum is represented using the green colored nodes in the binary tree.
Constraints:
1 β€ number of nodes β€ $10^3$
-10^4 β€ node->data β€ $10^4$
π― My Approach:
DFS Post-Order Traversal: Use a recursive DFS (post-order) approach to calculate, for each node:
maxSingle: The maximum path sum including the node and at most one of its subtrees.
Global Maximum: Update a global result with the sum of the node value and the maximum contributions from both left and right subtrees.
Steps:
Recursively compute the maximum path sum from the left and right children.
Discard negative sums by taking
max(0, value)
.Update the global maximum with
left + right + node->data
.Return
node->data + max(left, right)
to allow parent nodes to include the maximum available contribution.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as each node is visited exactly once.
Expected Auxiliary Space Complexity: O(h), where
h
is the height of the tree (due to the recursion stack). In the worst-case (skewed tree), this can be O(n).
π Solution Code
Code (C++)
class Solution {
int dfs(Node* r, int& res) {
if (!r) return 0;
int l = max(0, dfs(r->left, res)), rgt = max(0, dfs(r->right, res));
res = max(res, l + rgt + r->data);
return max(l, rgt) + r->data;
}
public:
int findMaxSum(Node* root) {
int res = INT_MIN;
dfs(root, res);
return res;
}
};
Code (Java)
class Solution {
int dfs(Node r, int[] res) {
if (r == null) return 0;
int l = Math.max(0, dfs(r.left, res)), rgt = Math.max(0, dfs(r.right, res));
res[0] = Math.max(res[0], l + rgt + r.data);
return Math.max(l, rgt) + r.data;
}
int findMaxSum(Node root) {
int[] res = {Integer.MIN_VALUE};
dfs(root, res);
return res[0];
}
}
Code (Python)
class Solution:
def findMaxSum(self, root):
def dfs(node):
if not node: return 0
l = max(0, dfs(node.left))
r = max(0, dfs(node.right))
nonlocal res
res = max(res, l + r + node.data)
return max(l, r) + node.data
res = float('-inf')
dfs(root)
return res
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated