1. Evaluate Max Path Through Every Node (Recomputation)
Intuition
For each node u in the tree, calculate maxPathDown(u->left) and maxPathDown(u->right). Sum them with u->val to find the max path turning at u. Repeat for all nodes.
When to apply: Basic baseline intuition.
Algorithm
- Step 1: Helper maxDown(node) computes max path sum going strictly downwards from node.
- Step 2: For current node: pathThroughNode = node.val + max(0, maxDown(left)) + max(0, maxDown(right)).
- Step 3: Recurse on left child and right child to find max path not passing through node.
- Step 4: Return overall max.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: int maxDown(TreeNode* node) { if (!node) return 0; int left = max(0, maxDown(node->left)); int right = max(0, maxDown(node->right)); return node->val + max(left, right); } int maxPathSum(TreeNode* root) { if (!root) return INT_MIN; int leftDown = max(0, maxDown(root->left)); int rightDown = max(0, maxDown(root->right)); int currentMax = root->val + leftDown + rightDown; int leftSub = maxPathSum(root->left); int rightSub = maxPathSum(root->right); return max({currentMax, leftSub, rightSub}); }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n^2)— For each of the n nodes, maxDown traverses the subtree in O(n) time. - Space complexity:
O(h)— Call stack up to O(h).