leetcode【DFS】-----113. Path Sum II(路径总和II)

1、题目描述

        

2、分析

        和上一道题很像,只不过需要的是在过程中保存路径,这样就需要一个全局变量来保存最终的结果。一般在涉及到DFS时需要保存结果什么需要全局变量来保存,这样才会保证其在递归的过程中保持原来的值。

3、代码

/**
 * 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) {
        if(root==NULL) return res;
        temp.push_back(root->val);
        if(root->left==NULL&&root->right==NULL&&sum-root->val==0){
             res.push_back(temp);
            }
        pathSum(root->left,sum-root->val);
        pathSum(root->right,sum-root->val);
        temp.pop_back();
        return res;
    }
private:
    vector<vector<int>> res;
    vector<int> temp;
};

4、相关知识点

        涉及到递归保存值的问题,需要使用全局变量来保存。

posted @ 2019-07-14 16:22  吾之求索  阅读(93)  评论(0)    收藏  举报