forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
53 lines (39 loc) · 957 Bytes
/
main.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
46
47
48
49
50
51
52
53
/// Source : https://leetcode.com/problems/sum-root-to-leaf-numbers/description/
/// Author : liuyubobobo
/// Time : 2018-10-16
#include <iostream>
using namespace std;
/// Recursion
/// Time Complexity: O(n)
/// Space Complexity: O(logn)
/// 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) {
if(!root) return 0;
int res = 0;
dfs(root, 0, res);
return res;
}
private:
void dfs(TreeNode* node, int tnum, int& sum){
tnum = tnum * 10 + node->val;
if(!node->left && !node->right)
sum += tnum;
else{
if(node->left)
dfs(node->left, tnum, sum);
if(node->right)
dfs(node->right, tnum, sum);
}
}
};
int main() {
return 0;
}