Leetcode 437. Path Sum III

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Path Sum III

2. Solution

  • Recursive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if(!root) {
return 0;
}
int paths = 0;
path(root, sum, paths);
return paths + pathSum(root->left, sum) + pathSum(root->right, sum);
}

void path(TreeNode* root, int sum, int& paths) {
if(root->val == sum) {
paths++;
}
if(root->left) {
path(root->left, sum - root->val, paths);
}
if(root->right) {
path(root->right, sum - root->val, paths);
}
}
};

Reference

  1. https://leetcode.com/problems/path-sum-iii/description/
如果有收获,可以请我喝杯咖啡!