LeetCode 113 Path Sum II The LeetCode Path of HERODING

Given a binary tree and a goal sum, find all the paths whose sum of paths from the root node to the leaf node is equal to the given goal sum.

Explanation: A leaf node refers to a node without child nodes.

Example:
Given the following binary tree, and the goal and sum = 22,

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \    / \
    7    2  5   1

return:

[
[5,4,11,2],
[5,8,4,5]
]

Problem-solving idea: It is
still a backtracking problem, depth-first traversal to each leaf node, and then judge whether the sum on the path is equal to sum, if it is not equal to return, and equal to it, put it in ans until all leaf nodes are traversed, the code is as follows :

/**
 * 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>> ans;
        vector<int> res;
        dfs(root, ans, res, sum); 
        return ans;
    }

    void dfs(TreeNode * root, vector<vector<int>> & ans, vector<int> & res, int sum){
    
    
        if(!root){
    
    
            return;
        }
        res.push_back(root->val);
        if(root->val == sum && (root->left == NULL && root->right == NULL)){
    
    
            ans.push_back(res);
        }
        dfs(root->left, ans, res, sum - root->val);
        dfs(root->right, ans, res, sum - root->val);
        res.pop_back();
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/108807470