-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path129
54 lines (43 loc) · 1.25 KB
/
129
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void find(TreeNode* root, vector<int> path, vector<vector<int>>& ans) {
if (root == nullptr)
return;
path.push_back(root->val);
if (root->left == nullptr && root->right == nullptr) {
ans.push_back(path);
return;
}
if (root->left != nullptr)
find(root->left, path, ans);
if (root->right != nullptr)
find(root->right, path, ans);
// Pop the last element from path after visiting both left and right subtrees
path.pop_back();
}
int sumNumbers(TreeNode* root) {
vector<int>path;
vector<vector<int>>ans;
find(root,path,ans);
int ans1=0;
for(auto i:ans){
string p="";
for(auto j:i){
p+=to_string(j);
}
ans1+=stoi(p);
}
return ans1;
}
};