Subproblem-based Approach for Resolving Max Value on Trees

There are two kinds of max problems on trees based on the approaches, for one type of problems, we usually use the subproblem strategy, while for the other type, we need to use cached DFS or DP.

The typical problems for the first category:

  1. Max depth of the tree: Maximum Depth of Binary Tree

  2. Diameter of the tree: Diameter of Binary Tree

The strategy is similar, we need to transfer the problem to subproblem on left and right children.

Max depth of the tree - node max depth = Math.max(left children depth, right children depth) + 1;

Diameter of the tree - node diameter = left children depth + right children depth;

    int maxDiameter = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        maxDepth(root);
        return maxDiameter;
    }
    private int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftMaxDepth = maxDepth(root.left);
        int rightMaxDepth = maxDepth(root.right);
        maxDiameter = Math.max(maxDiameter, leftMaxDepth + rightMaxDepth);
        return Math.max(leftMaxDepth, rightMaxDepth) + 1;
    }

Max path sum - node single side max path sum = left children single side max path sum + right children single side max path sum

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

}

Last updated