Leetcode之Path Sum II

topic:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

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

Return:

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

Code:

/**
 * 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 {
private:
    vector<vector<int>> res;
public:
    void helper(TreeNode* root,int sum,vector<int>& v){
        if(!root)return;
        if(!root->left&&!root->right){
            if(sum!=root->val)return;
            v.push_back(root->val);
            res.push_back(v);
            v.pop_back();
        }
        int value=sum-root->val;
        v.push_back(root->val);
        if(root->left)helper(root->left,value,v);
        if(root->right)helper(root->right,value,v);
        v.pop_back();
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<int> v;
        helper(root,sum,v);
        return res;
    }
};

idea:

Also you need pop_back (), understand!

Guess you like

Origin blog.csdn.net/qq_35455503/article/details/91492128