讨论/题目交流/124. 二叉树中的最大路径和/
124. 二叉树中的最大路径和

给定一个非空二叉树,返回其最大路径和。
本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
示例 1:

输入: [1,2,3]

       1
      / \
     2   3

输出: 6

示例 2:

输入: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

输出: 42

展开讨论
demongodYY发起于 2020-05-01
共 3 个讨论

简化成寻找单个节点作为根节点时,左边和右边的最大路径和。再遍历整个二叉树,比较每个节点的最大路径和,找出最大值。(其中左边或右边的最大值为负数时,考虑为0,意为不算上该部分。)

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */

var maxPathSum = function (root) {
    let result = -Infinity;

    const maxChildrenPathValue = function (node) { // 做出一条最大值的路径
        if (node == null) return 0;
        let leftPathVal = Math.max(maxChildrenPathValue(node.left), 0);
        let rightPathVal = Math.max(maxChildrenPathValue(node.right), 0);
        return Math.max(leftPathVal, rightPathVal) + node.val;
    }

    const getRootMaxPathVal = function (root) {   // 找出某个根节点的最大路径值
        const leftMaxPathVal = Math.max(maxChildrenPathValue(root.left), 0);
        const rightMaxPathVal = Math.max(maxChildrenPathValue(root.right),0);
        return leftMaxPathVal + rightMaxPathVal + root.val;
    }

    const preorderTraversal = function (root) {  // 前序遍历,找每个节点为根节点的最大路径值
        if (root) {
            const value = getRootMaxPathVal(root);
            if(value > result) result = value;  // 更新最大值
            preorderTraversal(root.left);
            preorderTraversal(root.right);
        }
    }
    
    preorderTraversal(root);
    
    return result;
};
var maxPathSum = function(root) {
    let max_sum = -Infinity;
    function max_gain (root) {
        if (root === null) {
            return 0;
        }

        const left_gain = Math.max(max_gain(root.left), 0);
        const right_gain = Math.max(max_gain(root.right), 0);

        const newPath = root.val + left_gain + right_gain;

        max_sum = Math.max(newPath, max_sum);

        return root.val + Math.max(left_gain, right_gain);
    }
    max_gain(root);
    return max_sum;
};
func maxPathSum(root *TreeNode) int {
    var val = INT_MIN();
	subMaxPathSum(root, &val);
	return val;
}

func subMaxPathSum(root *TreeNode,val *int) int{
	if (root == nil){
        return 0;
    } 
	left := subMaxPathSum(root.Left, val);
	right := subMaxPathSum(root.Right, val);
	threeSub := root.Val + max(0, left) + max(0, right);
    twoSub := root.Val + max(0, max(left, right));
	*val = max(*val, max(threeSub, twoSub));
	return twoSub;
}

func INT_MIN() int{
    const intMax = int(^uint(0) >> 1)
    return  ^intMax
}


func max(x, y int) int {
    if x < y {
        return y
    }
    return x
}