forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0129.cpp
More file actions
35 lines (32 loc) · 791 Bytes
/
0129.cpp
File metadata and controls
35 lines (32 loc) · 791 Bytes
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
/**
* 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:
int sumNumbers(TreeNode* root) {
int ans = 0;
int path = 0;
dfs(root, path, ans);
return ans;
}
private:
void dfs(TreeNode* root, int& path, int& ans) {
if (!root) return;
if (!root->left && !root->right) {
path = path * 10 + root->val;
ans += path;
path = (path - root->val) / 10;
return;
}
path = path * 10 + root->val;
dfs(root->left, path, ans);
dfs(root->right, path, ans);
path = (path - root->val) / 10;
}
};