[LeetCode] Sum Root to Leaf Numbers

129. 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.

A leaf node is a node with no children.

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
/**
* 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 {
int res = 0;
void helper(TreeNode* node, int sum) {
if(!node) return;
sum = sum * 10 + node->val;
if(!node->left and !node->right) {
res += sum;
} else {
helper(node->left, sum);
helper(node->right, sum);
}
}
public:
int sumNumbers(TreeNode* root) {
helper(root, 0);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/07/PS/LeetCode/sum-root-to-leaf-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.