Binary Tree Maximum Path Sum

本文介绍了一种求解二叉树中最大路径和的算法实现,该路径可以始于并结束于任意节点。通过递归辅助函数进行路径求解,并采用ResultType类存储中间结果。

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

class ResultType{
    int root2any;
    int any2any;
    ResultType(int root2any, int any2any){
        this.root2any = root2any;
        this.any2any = any2any;
    }
}

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int maxPathSum(TreeNode root) {
        return helper(root).any2any;
    }
    //分三种情况,从中取最大: 左子树的any2any, 右子树的any2any,跨根节点方案
    public ResultType helper(TreeNode root){
        if (root == null){
            //把null节点的any2any设为整数最小值以保证root为负时至少return一个值
            return new ResultType(0,Integer.MIN_VALUE);
        }
        //divide 
        ResultType left = helper(root.left);
        ResultType right = helper(root.right);
        
        
        //conquer
        int root2any = Math.max(0, Math.max(left.root2any,right.root2any)) + root.val;
        //比较方案1和方案2(左子树的any2any和右子树的any2any)
        int any2any = Math.max(left.any2any,right.any2any);
        //跨root情况
        any2any = Math.max(any2any, Math.max(0,left.root2any) + Math.max(0,right.root2any) + root.val);
        
        return new ResultType(root2any, any2any);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值