题解 | #牛群特殊路径的数量#
牛群特殊路径的数量
https://www.nowcoder.com/practice/1c0f95d8396a432db07945d8fe51a4f5
考察的知识点:二叉树的递归遍历;
解答方法分析:
- 定义了一个Solution类,其中有一个公有成员函数pathSum,用于计算二叉树中路径和等于给定值的路径数量。
- pathSum函数使用了递归的方法,首先判断当前节点是否为空,如果为空则返回0。
- 如果当前节点的值等于给定的sum值,计数器count加1。
- 递归调用pathSum函数计算左子树和右子树的路径和等于sum的路径数量,并将结果累加到count中。
- 最后返回count作为结果。
所用编程语言:C++;
完整编程代码:↓
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if (root == nullptr) {
return 0;
}
return pathSumHelper(root, sum) + pathSum(root->left,sum) + pathSum(root->right, sum);
}
int pathSumHelper(TreeNode* node, int sum) {
if (node == nullptr) {
return 0;
}
int count = 0;
if (node->val == sum) {
count++;
}
count += pathSumHelper(node->left, sum - node->val);
count += pathSumHelper(node->right, sum - node->val);
return count;
}
};
