您的位置:首页 > 其它

[Leetcode] #112#113 Path Sum I & II

2017-02-10 15:27 483 查看

Path Sum I:

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.

Solution:

bool hasPathSum(TreeNode* root, int sum) {
if (root == NULL)
return false;
if (root->val == sum && root->left == NULL && root->right == NULL)
return true;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}

Path Sum II:

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:

采用DFS,给出两种稍微不同的递归写法。void pathSum(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &res)
{
path.push_back(root->val);
sum -= root->val;
if (sum == 0 && !root->left && !root->right)
res.push_back(path);
if (root->left)
pathSum(root->left, sum, path, res);
if (root->right)
pathSum(root->right, sum, path, res);
path.pop_back();
}

vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> ans;
if (!root) return ans;
vector<int> path;
pathSum(root, sum, path, ans);
return ans;
}
void pathSum(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &res)
{
if (!root) return;
path.push_back(root->val);
sum -= root->val;
if (sum == 0 && !root->left && !root->right)
res.push_back(path);
pathSum(root->left, sum, path, res);
pathSum(root->right, sum, path, res);
path.pop_back();
}

vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> ans;
vector<int> path;
pathSum(root, sum, path, ans);
return ans;
}
GitHub-LeetCode: https://github.com/wenwu313/LeetCode
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: