[InterviewBit] Root to Leaf Paths With Sum

Root to Leaf Paths With Sum

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void dfs(TreeNode* A, vector<vector<int>>& res, vector<int>& now, int target, int sum) {
sum += A->val;
now.push_back(A->val);
if(!A->left and !A->right) {
if(target == sum) res.push_back(now);
}
if(A->left) dfs(A->left, res, now, target, sum);
if(A->right) dfs(A->right, res, now, target, sum);
now.pop_back();
}
vector<vector<int>> Solution::pathSum(TreeNode* A, int B) {
vector<vector<int>> res;
dfs(A,res,vector<int>() = {}, B, 0);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/05/PS/interviewbit/root-to-leaf-paths-with-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.