113. 路径总和 II

该题为112. 路径总和的升级版

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

Solution1:

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
38
39
40
41
42
43
/**
* 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<int> path;
vector<vector<int> > result;
if(root){
dfs(root,0,sum,path,result);
}
return result;
}

void dfs(TreeNode* node,int currentsum, int sum,vector<int> &path,vector<vector<int> > &result){
currentsum += node->val;

path.push_back(node->val);
//当到达叶子结点,并且路径之和与sum相同
if(node && !node->left && !node->right ){
if(currentsum == sum)
result.push_back(path);
return;
}
if(node->left){
dfs(node->left,currentsum,sum,path,result);
//回溯,还原状态
path.pop_back();
}
if(node->right){
dfs(node->right,currentsum,sum,path,result);
//回溯,还原状态
path.pop_back();
}

}
};

Solution2:

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
/**
* 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<int> path;
vector<vector<int> > result;
preorder(root,0,sum,path,result);
return result;
}
void preorder(TreeNode* node, int currentsum, int sum, vector<int> &path, vector<vector<int> > &result){
if(!node) return;
currentsum += node->val;
path.push_back(node->val);
if(!node->left && !node->right && currentsum == sum){
result.push_back(path);
}
preorder(node->left,currentsum,sum,path,result);
preorder(node->right,currentsum,sum,path,result);
//该步可有可无,因为只会递归到叶子节点才返回,又每次递归都在栈中保留了原来该值的副本。
// currentsum -= node->val;
path.pop_back();
}
};