您的位置:首页 > 其它

[LeetCode] Path Sum II

2017-09-10 20:43 134 查看
[Problem]
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]
]



[Solution]

//
// Definition for binary tree
// 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

vector<vector<int> > result;

// null root
if(root == NULL){
return result;
}
// leaf node
else if(root->left == NULL && root->right == NULL && root->val == sum){
vector<int> res;
res.push_back(sum);
result.push_back(res);
return result;
}
else{
// check left brunch
if(root->left != NULL){
vector<vector<int> > left = pathSum(root->left, sum - root->val);
for(int i = 0; i < left.size(); ++i){
left[i].insert(left[i].begin(), root->val);
result.push_back(left[i]);
}
}
// check right brunch
if(root->right != NULL){
vector<vector<int> > right = pathSum(root->right, sum - root->val);
for(int i = 0; i < right.size(); ++i){
right[i].insert(right[i].begin(), root->val);
result.push_back(right[i]);
}
}
return result;
}
}
};

 说明:版权所有,转载请注明出处。Coder007的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: