Total Leetcode 113. Path II and C ++ implementation solving ideas

Problem-solving ideas:

A typical problem of depth-first search or backtracking.

 

/**
 * 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>> res;
        vector<int> cur;
        dfs(root, res, cur, sum);
        return res;
    }
    void dfs(TreeNode* root, vector<vector<int> >& res, vector<int>& cur, int sum){
        if(!root) return;
        cur.push_back(root->val);
        if(root && !root->left && !root->right && sum == root->val) //叶子节点
            res.push_back(cur);
        
        dfs(root->left, res, cur, sum-root->val);
        dfs(root->right, res, cur, sum-root->val);
        cur.pop_back();
    }
};

 

 

Guess you like

Origin blog.csdn.net/gjh13/article/details/92211700