-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path129.求根到叶子节点数字之和.cpp
46 lines (40 loc) · 950 Bytes
/
129.求根到叶子节点数字之和.cpp
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
/*
* @lc app=leetcode.cn id=129 lang=cpp
*
* [129] 求根到叶子节点数字之和
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <string>
class Solution {
public:
int sumNumbers(TreeNode* root) {
if(root == nullptr) return 0;
DFS(root, "");
return sum;
}
private:
unsigned long long sum = 0;
void DFS(TreeNode* root, std::string&& s){
s.insert(s.end(), root->val + '0');
if(root->left != nullptr){
DFS(root->left, std::move(s));
}
if(root->right != nullptr){
DFS(root->right, std::move(s));
}
if(root->left == nullptr && root->right == nullptr){
sum += std::stoull(s);
}
s.erase(s.end() - 1);
}
};
// @lc code=end