-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0129-Sum_Root_to_Leaf_Numbers.cpp
More file actions
99 lines (92 loc) · 2.5 KB
/
0129-Sum_Root_to_Leaf_Numbers.cpp
File metadata and controls
99 lines (92 loc) · 2.5 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*******************************************************************************
* 0129-Sum_Root_to_Leaf_Numbers.cpp
* Billy.Ljm
* 14 Mar 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/sum-root-to-leaf-numbers/
* You are given the root of a binary tree containing digits from 0 to 9 only.
* Each root-to-leaf path in the tree represents a number. For example, the
* root-to-leaf path 1 -> 2 -> 3 represents the number 123. Return the total sum
* of all root-to-leaf numbers. Test cases are generated so that the answer will
* fit in a 32-bit integer.
*
* ===========
* My Approach
* ===========
* Recursively visit all the leaves in a depth-first-search manner, and sum up
* all root-to-leaf paths.
******************************************************************************/
#include <iostream>
/**
* 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:
/**
* Sums up all the the root-to-leaf numbers
*
* @param root root of tree to sum numbers from
*
* @return sum of all the root-to-leaf numbers
*/
int sumNumbers(TreeNode* root) {
if (root == nullptr) {
return 0;
}
else {
return recurse(root, 0);
}
}
private:
/**
* Recurses until leaf node, and sums both left and right numbers
*
* @param root root of tree to recursively traverse
* @param sum sum of parent nodes
*
* @returns sum of all root-to-leaf numbers passing through root
*/
int recurse(TreeNode* root, int sum) {
// sum up to current node
sum = sum * 10 + root->val;
// recursively sum up other nodes
if (root->left != nullptr and root->right != nullptr) {
return recurse(root->left, sum) + recurse(root->right, sum);
}
else if (root->left != nullptr) {
return recurse(root->left, sum);
}
else if (root->right != nullptr) {
return recurse(root->right, sum);
}
else {
return sum;
}
}
};
/**
* Test cases
*/
int main (void) {
Solution sol;
TreeNode* root;
// Test Case 1
root = new TreeNode(1, new TreeNode(2), new TreeNode(3));
std::cout << sol.sumNumbers(root) << std::endl;
delete root->left, root->right, root;
// Test Case 2
root = new TreeNode(4, new TreeNode(0),
new TreeNode(9, new TreeNode(5), new TreeNode(1)));
std::cout << sol.sumNumbers(root) << std::endl;
}