题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
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();
}
};
问:为什么第二个函数定义在第一个函数后,也没有提前声明。在第一个函数中调用第二个函数不报错?
答:在类中,成员函数可以直接访问和调用其他成员函数,不需要提前声明。因此,虽然第一个函数在定义之前调用了第二个函数,但由于它们都是类的成员函数,所以编译器可以正确识别和调用第二个函数。
查看1道真题和解析