您的位置:首页 > 其它

leetcode | Path Sum II

2015-07-03 18:48 323 查看
Path Sum II : https://leetcode.com/problems/path-sum-ii/

这里写图片描述



解析:

和上一题的区别就是,要记录所有能满足条件的路径。

要保存路径 : 保存当前的结果,并且每次递归后都要恢复递归前的结果;每当满足了保存条件(递归到叶子节点时),判断是否需要当前结果(path)保存下来。

叶节点时 sum == 0, 保存当前结果,然后逐步恢复递归前结果

叶节点时 sum != 0,不保存当前结果,然后逐步恢复递归前结果

/**
* 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>> result;
if (root == NULL)
return result;
vector<int> path; // 存储一条路径
path.push_back(root->val);
DFS(root, sum-(root->val), path, result);
return result;
}
void DFS(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &result) {
if (root == NULL)
return;
if (root->left == NULL && root->right == NULL && 0 == sum) {
result.push_back(path); // 整条路径已跑完;
return;
}
// 左子树非空,遍历左子树
if (root->left != NULL) {
path.push_back(root->left->val); // 先推进去,记忆该节点
DFS(root->left, sum-(root->left->val), path, result);
path.pop_back(); // 用完后需要清除最后一个,下一个路径(它的兄弟节点)还要用
}
// 右子树非空,遍历右子树
if (root->right != NULL) {
path.push_back(root->right->val);
DFS(root->right, sum-(root->right->val), path, result);
path.pop_back();// 恢复递归前结果
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: