您的位置:首页 > 其它

LeetCode(124) Binary Tree Maximum Path Sum

2014-12-02 16:55 405 查看
题目如下:

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

Return 6.

分析如下:

注意从NODE A开始向叶节点方向增长的的maximum path一共有一下这4种情况

1 NODE, 如下面这种情况,最大值就是node(value = 1)自己。

1

/ \

-2 -3

2 NODE + left child

1

/ \

2 -3

3 NODE + right child

1

/ \

-2 3

4 NODE + right child + right child

1

/ \

2 3

其中除了4是折线(下面代码中的twofold_path_max)外,1~3都是直线(下面代码中额left_onefold_max 和right_onefold_max)。

对于每个节点算出的这四个值,都和保存当前最大值的变量maximum_result进行比较,不断地刷新maximum_result的值。

我的代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int my_maxPathSum(TreeNode *root, int onefold_path_max, int twofold_path_max, int& max_result) {
        if (root == NULL) return 0;
        int left_onefold_max = my_maxPathSum(root->left, onefold_path_max, twofold_path_max, max_result); 
        int right_onefold_max = my_maxPathSum(root->right, onefold_path_max, twofold_path_max, max_result);
        int return_one_fold_max = 0;
        twofold_path_max = left_onefold_max + right_onefold_max + root->val; // node + left + right,作为最大值的候选
        left_onefold_max = (left_onefold_max)>0?(left_onefold_max + root->val):(root->val); //从node和node + left中选个最大值
        right_onefold_max = (right_onefold_max)>0?(right_onefold_max + root->val):(root->val);//从node和node + right中选个最大值
        return_one_fold_max = (right_onefold_max > left_onefold_max)? right_onefold_max:left_onefold_max;
        max_result = (max_result > right_onefold_max)? max_result:right_onefold_max; //Note: max_result是轮流地和candidate比较
        max_result = (max_result > left_onefold_max)? max_result:left_onefold_max;
        max_result = (max_result > twofold_path_max)? max_result:twofold_path_max;
        return return_one_fold_max;
    }
    int maxPathSum(TreeNode *root) {
        int max_result = INT_MIN;
        int onefold_path_max = 0;
        int twofold_path_max = 0;
        my_maxPathSum(root, onefold_path_max, twofold_path_max, max_result);
        return max_result;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: