LeetCode 113. 路径总和 II (回溯、路径记录)

路径总和 II
与112路径总和思路是一样的,只是在这里多了一个路径记录罢了。

/**
 * 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:
    int sum;
    vector<vector<int>> ans;
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        this->sum = sum;
        vector<int> list;
        dfs(root,0,list);
        return ans;
    }
    void dfs(TreeNode* root,int cnt,vector<int>&list){
        if(!root){
            return;
        }
        list.push_back(root->val);
        if(!root->left && !root->right){
            if(cnt+root->val==sum){
                ans.push_back(list);
            }
            return;
        }
        if(root->left){
            dfs(root->left,cnt+root->val,list);
            list.pop_back();
        }
        if(root->right){
            dfs(root->right,cnt+root->val,list);
            list.pop_back();
        }
    }
};

另一种风格的DFS写法。

/**
 * 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>> ans;
    int sum;
    vector<vector<int>> pathSum(TreeNode* root, int sum){   
        this->sum = sum;
        vector<int> list; 
        if(!root){
            return ans;
        }  
        list.push_back(root->val);
        dfs(root,root->val,list);
        return ans;
    }

    void dfs(TreeNode* root,int cnt,vector<int>&list){
        if(!root){
            return;
        }
        if(!root->left && !root->right){
            if(cnt==sum){
                ans.push_back(list);
                return;
            }
        }
        if(root->left){
            list.push_back(root->left->val);
            dfs(root->left,cnt+root->left->val,list);
            list.pop_back();
        }
        if(root->right){
            list.push_back(root->right->val);
            dfs(root->right,cnt+root->right->val,list);
            list.pop_back();
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章