Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.node

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

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);
    }
}
相关文章
相关标签/搜索