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);
    }
}
相關文章
相關標籤/搜索