首页 > 其他 > 详细

leetcode | Path Sum II

时间:2015-07-03 17:26:04      阅读:191      评论:0      收藏:0      [点我收藏+]

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();// 恢复递归前结果
        }
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode | Path Sum II

原文:http://blog.csdn.net/quzhongxin/article/details/46743531

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!