# 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](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
2. Diameter of the tree: [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/)
3. Max path sum: [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)

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;

```java
    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

```java
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;
  }

}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coding.bea.ai/tree/typical-problems-and-solutions/subproblem-based-approach-for-resolving-max-value-on-trees.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
