Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
leetcode 113. Path sum II Medium
Subject description:
Given a binary tree and a target and to find the sum of all paths from the root node of the leaf node is equal to a given target and path.
Description: leaf node is a node has no child nodes.
Problem-solving ideas:
dfs
Code:
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(root==nullptr)
return {};
vector<vector<int>> res;
vector<int> out;
dfs(root,0,sum,res,out);
return res;
}
void dfs(TreeNode *root, int cur,int target,vector<vector<int>> &res,vector<int> &out){
if(root==nullptr)
return;
cur += root->val;
out.push_back(root->val);
if(!root->left && !root->right && cur==target){
res.push_back(out);
}
dfs(root->left,cur,target,res,out);
dfs(root->right,cur,target,res,out);
out.pop_back();
}
};