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();// 恢复递归前结果
        }
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/quzhongxin/article/details/46743531