Leetcode 113. Path Sum II

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

1. Description

Path Sum II

2. Solution

2.1 Recursive

  • Version 1
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
33
34
/**
* 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:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> result;
if(!root) {
return result;
}
vector<int> path;
tranverseTree(root, sum, result, path);
return result;
}

void tranverseTree(TreeNode* root, int sum, vector<vector<int>>& result, vector<int> path) {
path.push_back(root->val);
if(root->val == sum && root->left == NULL && root->right == NULL) {
result.push_back(path);
}
if(root->left) {
tranverseTree(root->left, sum - root->val, result, path);
}
if(root->right) {
tranverseTree(root->right, sum - root->val, result, path);
}
}
};
  • Version 2
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
33
34
35
36
37
/**
* 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:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> result;
if(!root) {
return result;
}
vector<int> path;
tranverseTree(root, sum, result, path);
return result;
}

void tranverseTree(TreeNode* root, int sum, vector<vector<int>>& result, vector<int>& path) {
path.push_back(root->val);
if(root->val == sum && root->left == NULL && root->right == NULL) {
result.push_back(path);
path.pop_back();
return;
}
if(root->left) {
tranverseTree(root->left, sum - root->val, result, path);
}
if(root->right) {
tranverseTree(root->right, sum - root->val, result, path);
}
path.pop_back();
}
};

Reference

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