LeetCode 124. Binary Tree Maximum Path Sum

Tech In Pieces發表於2020-11-19

Given a non-empty binary tree, find the maximum path sum.
For this problem****, a path is defined as any node sequence from some starting node to any node in the tree along the parent-child connections.**** The path must contain at least one node and does not need to go through the root.

也就是說 不一定是路徑 可以是任何一條路,而root可以是其中的任何一箇中間點。
just assume any node can be the inner node of the final results.

but my idea is totally wrong. I don’t even know what I’m doing.

class Solution {
    private int max = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        if (root == null) return 0;
        
        maxPass(root);
        return Math.max(maxPathSum(root.left), maxPathSum(root.right));
    }
    
    private int maxPass(TreeNode root) {
        if (root == null) return 0;
        max = Math.max(max, root.val + maxPass(root.left) + maxPass(root.right));
        return root.val + maxPass(root.left) + maxPass(root.right);
    }
}

but the correct solution is as follows, but it’s so hard to understand.
however, I find some good explainations:

Each node actually has two roles when it comes to function maxPathDown. When processing the final result maxValue, the node is treated as the highest point of a path. When calculating its return value, it is only part of a path (left or right part), and this return value will be used to calculate path sum of other paths with some other nodes(above the current one) as their highest point.

class Solution {
    private int res = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        if(root == null) return 0;
        
        helper(root);
        return res;
    }
    private int helper(TreeNode root){ //
        
        if(root == null) return 0;
        int left = Math.max(0, helper(root.left)); //如果左邊要是小於0 那還不如根本不走left
        int right = Math.max(0, helper(root.right)); //同理
        res = Math.max(res, left + right + root.val); //root作為路徑最高點
        return Math.max(left, right) + root.val; //往下走必須選擇左或者右的最高點。
    }
}

相關文章