题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
#include <vector>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param target int整型 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > FindPath(TreeNode* root, int target) {
        // write code here
        vector<vector<int> > res;
        vector<int> path;
        int currentSum = 0;
        
        if (root == nullptr)
            return res;

        FindPath(root, target, path, res, currentSum);
        return res;
    }

    void FindPath(TreeNode* root, int target, vector<int> &path, vector<vector<int> > &res, int ¤tSum) {
        currentSum += root->val;
        path.push_back(root->val);

        bool isLeaf = root->left == nullptr && root->right == nullptr;
        if (isLeaf && currentSum == target)
            res.push_back(path);
        
        if (root->left != nullptr)
            FindPath(root->left, target, path, res, currentSum);
        if (root->right != nullptr)
            FindPath(root->right, target, path, res, currentSum);
        
        currentSum -= root->val;
        path.pop_back();
    }
};

问:为什么第二个函数定义在第一个函数后,也没有提前声明。在第一个函数中调用第二个函数不报错?

答:在类中,成员函数可以直接访问和调用其他成员函数,不需要提前声明。因此,虽然第一个函数在定义之前调用了第二个函数,但由于它们都是类的成员函数,所以编译器可以正确识别和调用第二个函数。

全部评论

相关推荐

牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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