您的位置:首页 > 其它

Path Sum II问题及解法

2017-08-11 19:34 411 查看
问题描述:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
示例:
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]
]


问题分析:

一个典型的DFS问题,将root到leaf路径上的和加起来与sum进行比较,相等则保留,不相等则不保留。

过程详见代码:

/**
* 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<vector<int>> res;
vector<int> re;
bl(root, res, re, sum);
return res;
}

void bl(TreeNode* root,vector<vector<int>> & res, vector<int>& re, int sum)
{
if (root == NULL) return;

if (root->val == sum && root->left == NULL && root->right == NULL)
{
re.push_back(root->val);
res.push_back(re);
re.pop_back();
return;
}
re.push_back(root->val);
bl(root->left, res, re, sum - root->val);
re.pop_back();
re.push_back(root->val);
bl(root->right, res, re, sum - root->val);
re.pop_back();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: