题解 | #牛群特殊路径的数量#

牛群特殊路径的数量

https://www.nowcoder.com/practice/1c0f95d8396a432db07945d8fe51a4f5

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

题目解答方法的文字分析:要寻找一条路径的和是否等于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;
    }
};

全部评论

相关推荐

11-04 19:05
已编辑
东莞城市学院 单片机
不知道怎么取名字_:你这个要实习两年?哪有这么久的,感觉就是即使你毕业了,但还按实习的话,是不是不用给你缴社保公积金啥的
点赞 评论 收藏
分享
09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务