LeetCode--binary-tree-maximum-path-sum
2018-01-05 20:33
323 查看
题目描述
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 3
Return6.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/**
* 计算二叉树的最大路径和
* @param : root 二叉树根结点
* @return : 最大路径和
*/
int maxPathSum(TreeNode *root) {
if (root == NULL) return 0;
int tmpMax = root->val;
maxChildPathSum(root, &tmpMax);
return tmpMax;
}
private:
/**
* 计算二叉树子树的最大路径和以及整棵二叉树的最大路径和
* 子树路径必须以根结点开始,以树中某一结点结束
* 二叉树的最大路径和的路径,不必以根结点为开始结点
* @param : root 二叉树根结点
* @param : tmpMax 暂存整棵二叉树的最路径和的变量的地址
* @return : 子树的最大路径和
*/
int maxChildPathSum(TreeNode *root, int *tmpMax) {
if (root == NULL) return 0;
/* 计算左右子树的最大路径和 */
int leftMax = maxChildPathSum(root->left, tmpMax);
int rightMax = maxChildPathSum(root->right, tmpMax);
/* 尝试更新整棵二叉树的最大路径和 */
int tmp = root->val;
if (leftMax > 0) tmp += leftMax;
if (rightMax > 0) tmp += rightMax;
if (tmp > *tmpMax) *tmpMax = tmp;
/* 计算并返回子树的最大路径和 */
int maxRoot = max(root->val, max(root->val + leftMax, root->val + rightMax));
return maxRoot;
}
};
相关文章推荐
- [leetcode]Binary Tree Maximum Path Sum
- LeetCode:Binary Tree Maximum Path Sum
- [leetcode]Binary Tree Maximum Path Sum
- LeetCode "Binary Tree Maximum Path Sum"
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum, 解题报告
- [LeetCode] Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum -- leetcode
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- LeetCode Week5:Recover Binary Search Tree、Binary Tree Maximum Path Sum
- LeetCode124 Binary Tree Maximum Path Sum
- Java for LeetCode 124 Binary Tree Maximum Path Sum
- Leetcode 124 Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum(递归)
- LeetCode 124: Binary Tree Maximum Path Sum 树形动态规划
- LeetCode:Binary Tree Maximum Path Sum
- leetcode--Binary Tree Maximum Path Sum