标签:c style class blog code java
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,1 / 2 3Return
6
.
这个问题可以转化为,以某节点作为祖先,并经过这一节点的和最大的路径。
于就其实就是要遍历每一个节点,并对此节点求出
1. 以此节点作为祖先节点
2. 和最大的路径
然后比较得出全局最大。
当前节点的最大和为
maxSum = max(
maxSingleSum(root->left),
maxSingleSum(root->right),
maxSingleSum(root->left) + maxSingleSum(root->right),
0) + root->val
maxSingleSum是单侧和最大的路径,另外不要忘了比较最后的0,因为单侧路径和小于0对求最大和是没有贡献的。
这里注意到,这里递归实现时其实只需要传maxSingleSum,而maxSum可作为全局的变量进行更新。看代码:
1 class Solution { 2 public: 3 int maxPathSum(TreeNode *root) { 4 int maxSum = INT_MIN; 5 maxPathSumImpl(root, maxSum); 6 return maxSum; 7 } 8 private: 9 int maxPathSumImpl(TreeNode* root, int& maxSum) { 10 if (root == NULL) 11 return 0; 12 int left = maxPathSumImpl(root->left, maxSum); // 左侧单边 13 int right = maxPathSumImpl(root->right, maxSum); // 右侧单边 14 int curMax = root->val; 15 if (left > 0) // 大于零时才有贡献 16 curMax += left; 17 if (right > 0) // 同上 18 curMax += right; 19 maxSum = max(maxSum, curMax); // 全局最大 20 int single = root->val + max(0, max(left, right)); // 单边最大 21 return single; 22 } 23 };
Leetcode OJ: Binary Tree Maximum Path Sum,布布扣,bubuko.com
Leetcode OJ: Binary Tree Maximum Path Sum
标签:c style class blog code java
原文地址:http://www.cnblogs.com/flowerkzj/p/3779151.html