您的位置:首页 > 其它

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: