Crack LeetCode 之 124. Binary Tree Maximum Path Sum
阿新 • • 發佈:2018-12-16
https://leetcode.com/problems/binary-tree-maximum-path-sum/
本題的難點在於每條路徑可以由樹中的任意兩個節點相連組成,解題方法還是遞迴。需要注意的是遞迴函式的返回值不是子樹的和,而是包含根節點的左子樹、根節點或者包含根節點的右子樹,這也是本題的遞迴函式和其他題目不同的地方。本題的時間複雜度是O(n),空間複雜度也是O(n)。以下是C++程式碼和python程式碼。
class Solution { public: int maxPathSum(TreeNode * root) { if (root == NULL) return 0; int res = root->val; helper(root, res); return res; } int helper(TreeNode * root, int & res) { if (root == NULL) return 0; int left = helper(root->left, res); int right = helper(root->right, res); int cur = root->val + (left>0 ? left : 0) + (right>0 ? right : 0); if (cur>res) res = cur; return root->val + max(left, max(right, 0)); } };
class Solution: maxVal = 0 def maxPathSum(self, root): if root == None: return 0 maxVal = root.val self.helper(root) return maxVal def helper(self): if root == None: return 0 left = helper(root.left); right = helper(root.right); cur = root.val + max(left, 0) + max(right, 0) if cur > maxVal: maxVal = cur return root.val + max(left, max(right,0))