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

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

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();
    }
};

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

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

全部评论

相关推荐

02-26 13:56
已编辑
重庆财经学院 Java
King987:你有实习经历,但是写的也太简单了,这肯定是不行的,你主要要包装实习经历这一块,看我的作品,你自己包装一下吧,或者发我,我给你出一期作品
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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