【LeetCode】81. Binary Tree Maximum Path Sum
阿新 • • 發佈:2018-12-12
題目描述(Hard)
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
題目連結
Example 1:
Input: [1,2,3]
1 / \ 2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10 / \ 9 20 / \ 15 7
Output: 42
演算法分析
類似【劍指】42.連續子陣列的最大和,對於有兩個方向的二叉樹,先算出左右子樹的結果L和R,如果L>0,那麼對於後續結果是有利的,我們加上L,R同理。最後返回值應只返回一個方向上的值,因為遞迴只能向父節點返回。
如Example2中所示,路徑為15->20->7。
提交程式碼:
class Solution { public: int maxPathSum(TreeNode* root) { int max_sum = INT_MIN; dfs(root, max_sum); return max_sum; } int dfs(TreeNode* root, int& max_sum) { if (!root) return 0; int left = dfs(root->left, max_sum); int right = dfs(root->right, max_sum); int curr = root->val; if (left > 0) curr += left; if (right > 0) curr += right; max_sum = max(max_sum, curr); return max(left, right) > 0 ? max(left, right) + root->val : root->val; } };