标签:style blog http color io strong for ar div
LeetCode: Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5
/ 4 8
/ / 11 13 4
/ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
地址:https://oj.leetcode.com/problems/path-sum/
算法:用递归应该很简单吧。直接看代码吧:
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 bool hasPathSum(TreeNode *root, int sum) {
13 if(!root) return false;
14 return subSolution(root,sum);
15 }
16 bool subSolution(TreeNode *root, int sum){
17 if(!root->left && !root->right){
18 if(sum == root->val) return true;
19 else return false;
20 }else{
21 if(root->left){
22 bool left = subSolution(root->left,sum - root->val);
23 if(left) return true;
24 }
25 if(root->right){
26 bool right = subSolution(root->right,sum - root->val);
27 if(right) return true;
28 }
29 }
30 return false;
31 }
32 };
第二题:
Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5
/ 4 8
/ / 11 13 4
/ \ / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
地址:https://oj.leetcode.com/problems/path-sum-ii/
算法:跟上一题一样,只不过必须返回所有的结果。应该也很简单,直接看代码:
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 vector<vector<int> > pathSum(TreeNode *root, int sum) {
13 if(!root) return vector<vector<int> >();
14 return subPathSum(root,sum);
15 }
16 vector<vector<int> > subPathSum(TreeNode *root, int sum){
17 if(!root->left && !root->right){
18 if(root->val == sum){
19 return vector<vector<int> >(1,vector<int>(1,sum));
20 }else{
21 return vector<vector<int> >();
22 }
23 }
24 vector<vector<int> > result;
25 if(root->left){
26 vector<vector<int> > left = subPathSum(root->left, sum - root->val);
27 vector<vector<int> >::iterator it = left.begin();
28 for(; it != left.end(); ++it){
29 vector<int> temp;
30 temp.push_back(root->val);
31 temp.insert(temp.end(),it->begin(),it->end());
32 result.push_back(temp);
33 }
34 }
35 if(root->right){
36 vector<vector<int> > right = subPathSum(root->right,sum - root->val);
37 vector<vector<int> >::iterator it = right.begin();
38 for(; it != right.end(); ++it){
39 vector<int> temp;
40 temp.push_back(root->val);
41 temp.insert(temp.end(),it->begin(),it->end());
42 result.push_back(temp);
43 }
44 }
45 return result;
46 }
47 };
标签:style blog http color io strong for ar div
原文地址:http://www.cnblogs.com/boostable/p/leetcode_path_sum.html