forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
129_Sum_Root_to_Leaf_Numbers
67 lines (59 loc) · 1.75 KB
/
129_Sum_Root_to_Leaf_Numbers
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
55
56
57
58
59
60
61
62
63
64
65
66
67
Leetcode 129: Sum Root to Leaf Numbers
--------------------------------------
Detailed Explanation can be found here: https://youtu.be/tanL9EJVfrU
C++:
----
class Solution {
public:
int sumNumbers(TreeNode* root) {
if(!root) return 0;
int result = 0;
findsum(root, 0, result);
return result;
}
void findsum(TreeNode* root, int val, int& result) {
int curr = val*10 + root->val;
if(!root->left && !root->right){
result += curr;
return;
}
if(root->left) findsum(root->left, curr, result);
if(root->right) findsum(root->right, curr, result);
}
};
Java:
-----
class Solution {
private int result;
private void findsum(TreeNode root, int val) {
int curr = val*10 + root.val;
if(root.left == null && root.right == null){
result += curr;
return;
}
if(root.left != null) findsum(root.left, curr);
if(root.right != null) findsum(root.right, curr);
}
public int sumNumbers(TreeNode root) {
if(root == null) return 0;
result = 0;
findsum(root, 0);
return result;
}
}
Python3:
--------
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
if root == None: return 0
self.result = 0
self.findsum(root, 0)
return self.result
def findsum(self, root, val):
curr = val*10 + root.val
if root.left == None and root.right == None:
self.result += curr
return
if root.left != None: self.findsum(root.left, curr)
if root.right != None: self.findsum(root.right, curr)
****** Please Subscribe Knowledge Center: http://youtube.com/c/KnowledgeCenter ********