您的位置:首页 > 职场人生

[LeetCode] Path Sum II

2014-01-04 11:21 357 查看
问题:

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]
]

分析:
有点像permutation那道题。

代码:

class Solution {
public:
void pathSum(vector<vector<int> > &result, vector<int> temp, TreeNode *root, int sum) {
if (!root) return;
if (root->val == sum && !root->left && !root->right) {
temp.push_back(root->val);
result.push_back(temp);
return;
}
else {
temp.push_back(root->val);
pathSum(result, temp, root->left, sum - root->val);
pathSum(result, temp, root->right, sum - root->val);
}
}

vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > result;
vector<int> temp;
pathSum(result, temp, root, sum);
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 面试