LeetCode 124 Binary Tree Maximum Path Sum (C++, Python)
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
Given the below binary tree,
1 / \ 2 3
Return
6
.Solution C++
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 | /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: int dfsMaxPathSum(TreeNode* node, int& sum) { if (node == NULL) return 0; int left = 0; if (node->left) left = dfsMaxPathSum(node->left, sum); int right = 0; if (node->right) right = dfsMaxPathSum(node->right, sum); int cur = node->val; if (left > 0) { cur += left; } if (right > 0) { cur += right; } sum = max(cur, sum); int tmp = max(left, right); return tmp > 0? tmp + node->val: node->val; } public: int maxPathSum(TreeNode *root) { int sum = numeric_limits<int>::min(); dfsMaxPathSum(root, sum); return sum; } }; |
Solution Python
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 | # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def intMaxPathSum(self, node, ret): if not node: return 0 cur = node.val left = self.intMaxPathSum(node.left, ret) right = self.intMaxPathSum(node.right, ret) if left > 0: cur += left if right > 0: cur += right ret[0] = max(ret[0], cur) tmp = max(left, right) return tmp + node.val if (tmp > 0) else node.val # @param root, a tree node # @return an integer def maxPathSum(self, root): ret = [- 2 ** 31] self.intMaxPathSum(root, ret) return ret[0] |