124. Binary Tree Maximum Path Sum
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node’s values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.
new solution update 2022.03.10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 class Solution { int res = INT_MIN; int helper (TreeNode* node) { if (!node) return 0 ; int leftSum = helper (node->left); int rightSum = helper (node->right); int innerSum = max ({node->val + leftSum, node->val + rightSum, node->val + leftSum + rightSum, node->val}); res = max (res, innerSum); int pathSum = max ({node->val, leftSum + node->val, rightSum + node->val}); return pathSum; } public : int maxPathSum (TreeNode* root) { helper (root); return res; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 class Solution { pair<int , int > search (TreeNode* node) { if (node->left and node->right) { auto [leftPathToParent, leftPathInner] = search (node->left); auto [rightPathToParent, rightPathInner] = search (node->right); return {max (max (leftPathToParent, rightPathToParent) + node->val, node->val), max ({leftPathInner, rightPathInner, leftPathToParent + rightPathToParent + node->val, node->val, max (leftPathToParent, rightPathToParent) + node->val})}; } else if (node->left) { auto [leftPathToParent, leftPathInner] = search (node->left); return {max (leftPathToParent + node->val, node->val), max ({leftPathInner, leftPathToParent + node->val, node->val, leftPathToParent})}; } else if (node->right) { auto [rightPathToParent, rightPathInner] = search (node->right); return {max (rightPathToParent + node->val, node->val), max ({rightPathInner, rightPathToParent + node->val, node->val, rightPathToParent})}; } else { return {node->val, node->val}; } } public : int maxPathSum (TreeNode* root) { auto [pathToParent, pathInner] = search (root); return max (pathToParent, pathInner); } };