Binary Tree Maximum Path Sum

本文探讨了如何在二叉树中找到最大的路径和。通过分析三种可能的情况,即只使用当前节点、使用单侧子树或同时使用两侧子树,作者提供了求解该问题的算法实现。关键在于正确初始化最大值并正确比较单侧和双侧路径的贡献。

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.

思路: There are only some situation in this question. 1 . Using this node's sub tree or not. 2. Only using one side sub tree or both sides.
两种情况,以root 为转折点, 穿过root向上。穿过root向上有三种情况,root + left, root + right, root

易错点: 1. Max 一定要初始化为 Integer.MIN_VALUE;  2 一定要注意 只用当前节点 和 用单边节点的比较。 3.  子函数 返回的是 cur , 不是 max, 只有穿过root 的才能返回。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root) {
        if(root == null)
            return 0;
        int[] max = new int[1];
        max[0] = Integer.MIN_VALUE;
        getMax(root, max);
        return max[0];
    }
    
    public int getMax(TreeNode root, int[] max){
        if(root == null)
            return 0;
        int leftMax = getMax(root.left, max);
        int rightMax = getMax(root.right, max);
        int cur = Math.max(Math.max(leftMax, rightMax), 0 ) + root.val;//穿过root向上有三种情况,root + left, root + right, root
        max[0] = Math.max(max[0], Math.max(cur, leftMax + rightMax + root.val));//两种情况,以root 为转折点, 穿过root向上。
        return cur;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值