LeetCode OJ-- Binary Tree Maximum Path Sum ***

https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/

给一棵二叉树,路径可以从任一点起,到任一点结束,但是可以连成一个路径的。求路径上最大和。

一般来说,路径是 V 字状的, 递归解的话, 每个点记录它的 左右子树的最大 V 值,并且和其的 V值相比较, 选最大的那个返回。

同时,为了计算它自己的 V 值,需要保留着,它左子树的 最大 path和,右子树的最大 path 和,这个path指的是 直的,没拐弯的。

注意,要对路径的值为负数的时候的处理。

/**
 * 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 maxPathSum(TreeNode *root) {
        if(root == NULL)
            return 0;
        
        int ans = 0;
        calcV(root, ans);
        return ans;
    }
    // return data is the biggest path
    int calcV(TreeNode* root, int &current_biggest_v)
    {
        if(root == NULL)
        {
            current_biggest_v = 0;
            return 0;
        }
        if(root->left == NULL && root->right == NULL)
        {
            current_biggest_v = root->val;
            return root->val;
        }
        int left_biggest_v;
        int right_biggest_v;
        
        int left_path = calcV(root->left, left_biggest_v);
        int right_path = calcV(root->right, right_biggest_v);
        
        int ret_val = 0;
        
        ret_val = max(left_path, right_path);
        ret_val = max(ret_val, 0);
        ret_val = ret_val + root->val;
        
        // with ? statements, with should add bracks
        int current_v = (left_path>0? left_path:0) +( right_path>0? right_path:0) + root->val;
        
        if(root->left && root->right == NULL)
            current_biggest_v = max(left_biggest_v, current_v);
        else if(root->right && root->left == NULL)
            current_biggest_v = max(right_biggest_v, current_v);
        else
        {
            current_biggest_v = max(left_biggest_v, right_biggest_v);
            current_biggest_v = max(current_biggest_v, current_v);
        }
         
        return ret_val;
    }
};
原文地址:https://www.cnblogs.com/qingcheng/p/3834728.html