Leetcode 129. Sum Root to Leaf Numbers
The problem “Sum Root to Leaf Numbers” is defined as follows:
Given a binary tree where each node contains a single digit (0-9), each root-to-leaf path could represent a number. An example of this would be from the root to the leaf being 1→2→3, which represents the number 123. The goal is to find the total sum of all the numbers represented by the different root-to-leaf paths in the tree.
To solve this problem, we can use Depth-First Search (DFS) to traverse the tree. During the traversal:
current_number = current_number * 10 + node->val
.current_number
to the total sum.Here’s how we can implement this in C++:
/**
* 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:
int sumNumbers(TreeNode* root) {
return dfs(root, 0);
}
private:
int dfs(TreeNode* node, int currentSum) {
if (!node) return 0;
currentSum = currentSum * 10 + node->val;
// If it's a leaf node, return the current sum.
if (!node->left && !node->right) {
return currentSum;
}
// Otherwise, proceed to the left and right children.
int leftSum = dfs(node->left, currentSum);
int rightSum = dfs(node->right, currentSum);
return leftSum + rightSum;
}
};
n
is the number of nodes in the tree.
h
is the height of the tree.
This ensures an efficient traversal and summation of all root-to-leaf numbers in the tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?