# Problem 437: Path Sum III

> <https://leetcode.com/problems/path-sum-iii/>

## 思路

* 这道题相当于是两部分的递归，第一部分递归这个树，对于每个 root，设计到了第二部分的递归 -- 求 count 数
* 这两部分的递归一定要先想清楚，否则主函数的 return 很容易写错

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int pathSum(TreeNode root, int sum) {
        if (root == null) return 0;

        return countPath(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
    }

    private int countPath(TreeNode root, int sum) {
        if (root == null) return 0;

        int count = 0;
        if (root.val == sum) count++;
        count += countPath(root.left, sum - root.val);
        count += countPath(root.right, sum - root.val);

        return count;
    }
}
```


---

# 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://liuyang89116.gitbook.io/my-leetcode-book/chapter_1_combination_and_permutation/binary-tree-path-sum/problem-437-path-sum-iii.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.
