题目考察的知识点:二叉树的遍历

题目解答方法的文字分析:要寻找一条路径的和是否等于sum,可以遍历每一个结点到空指针的和,然后找出符合条件的路径。

本题解析所用的编程语言:c++

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return int整型
     */
    void ispath(TreeNode* root, int& sum, int& count, int x)//找出符合的路径
    {
        if (root == nullptr)
            return;
        x += root->val;
        if (x == sum)
            ++count;
        ispath(root->left, sum, count, x);
        ispath(root->right, sum, count,x);
    }
    void Iordered(TreeNode* root, int& sum, int& count)//遍历每一个结点
    {
        if (root == nullptr)
            return;
        ispath(root, sum, count, 0);
        Iordered(root->left, sum, count);
        Iordered(root->right, sum, count);
    }
    int pathSum(TreeNode* root, int sum) {
        // write code here
        int count = 0;
        Iordered(root, sum, count);
        return count;
    }
};