124. Binary Tree Maximum Path Sum

# Hard, DFS

两个维度去分析这个问题

这个hard问题可以拆分成两个小问题:

  1. 自根节点往下,总和最大路径

  2. 左子树或右子树,总和最大路径

这是一个需要分而治之去解决的问题,需要知道哪些信息(如何分):

  1. 左边总和最大的路径,自根节点向下左边总和最大路径

  2. 右边总和最大的路径,自根节点向下右边总和最大路径

  3. 横跨左右包括root的最大路径

如何合并:以上三点,取最大路径

一定要会写test case,例如[-1], [-1, -2, -3], [1, 2].

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int maxPath = Integer.MIN_VALUE;
    
    public int maxPathSum(TreeNode root) {
        pathHelper(root);
        return maxPath;
    }
    
    public int pathHelper(TreeNode root) {
        // stop condition
        if(root == null) return Integer.MIN_VALUE;
        
        int left = pathHelper(root.left);
        int right = pathHelper(root.right);
        int singlePath = Math.max(Math.max(left, right), 0) + root.val;
        int rootPath = Math.max(left, 0) + Math.max(right, 0) + root.val;
        maxPath = Math.max(Math.max(singlePath, rootPath), maxPath);
        
        return singlePath;
    }
}

Last updated

Was this helpful?