lintcode-94-二叉树中的最大路径和

94-二叉树中的最大路径和

给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)

样例

给出一棵二叉树:

返回 6

标签

动态规划 分治法 递归

思路

找出某节点最大和次大路径,合并这两条路径即为最大路径和。

code

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    int maxPathSum(TreeNode *root) {
        int maxSum = 0x80000000;
        findMaxSum(root, maxSum);
        return maxSum;
    }

    int findMaxSum(TreeNode *root, int &curMax) {
        // write your code here
        int maxLeft = 0, maxRight = 0, maxValue = 0;

        if(root == NULL) {
            return 0;
        }

        maxLeft = findMaxSum(root->left, curMax);
        maxRight = findMaxSum(root->right, curMax);

        int temp = (0>maxLeft?0:maxLeft) + (0>maxRight?0:maxRight) + root->val;
        curMax = curMax > temp ? curMax : temp;


        return ( 0>(maxRight>maxLeft?maxRight:maxLeft) ? 0 : (maxRight>maxLeft?maxRight:maxLeft) ) + root->val;
    }
};
原文地址:https://www.cnblogs.com/libaoquan/p/7150892.html