KatInterview

129. Sum Root to Leaf Numbers

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to compute the sum of all numbers formed by root-to-leaf paths in a binary tree. Each node in the tree contains a single digit from 0 to 9. A path from the root to a leaf, such as 1 -> 2 -> 3, represents the number 123. We need to find all such numbers and sum them up.

Solution

Sum Root to Leaf Numbers in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumNumbers(self, root: Optional[TreeNode]) -> int:
        
        def dfs(node: Optional[TreeNode], current_sum: int) -> int:
            # If the node is null, this path is invalid.
            if not node:
                return 0
            
            # Update the current sum by appending the current node's value.
            # Python integers handle arbitrary size, so no overflow issues.
            current_sum = current_sum * 10 + node.val
            
            # If it's a leaf node, return the number for this path.
            if not node.left and not node.right:
                return current_sum
            
            # If it's an internal node, return the sum of numbers from subtrees.
            return dfs(node.left, current_sum) + dfs(node.right, current_sum)

        # Initial call to the recursive helper function.
        return dfs(root, 0)

Sum Root to Leaf Numbers in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int sumNumbers(TreeNode root) {
        // Initial call to the recursive helper function.
        // The result is cast to int as the problem guarantees it fits.
        return (int)dfs(root, 0L);
    }
    
    // Helper function to perform DFS and calculate sum.
    // Uses long to prevent overflow for path numbers.
    private long dfs(TreeNode node, long currentSum) {
        // If the node is null, this path contributes nothing to the sum.
        if (node == null) {
            return 0;
        }
        
        // Update the current sum by appending the current node's value.
        currentSum = currentSum * 10 + node.val;
        
        // If it's a leaf node, we have formed a complete number.
        // Return this number to be summed up.
        if (node.left == null && node.right == null) {
            return currentSum;
        }
        
        // If it's not a leaf node, continue the traversal.
        // The total sum for this subtree is the sum from left and right subtrees.
        return dfs(node.left, currentSum) + dfs(node.right, currentSum);
    }
}

Sum Root to Leaf Numbers 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) {
        // Initial call to the recursive helper function.
        // The result is cast to int as the problem guarantees it fits.
        return (int)dfs(root, 0);
    }

private:
    // Helper function to perform DFS and calculate sum.
    // Uses long long to prevent overflow for path numbers.
    long long dfs(TreeNode* node, long long currentSum) {
        // If the node is null, this path contributes nothing to the sum.
        if (node == nullptr) {
            return 0;
        }

        // Update the current sum by appending the current node's value.
        currentSum = currentSum * 10 + node->val;

        // If it's a leaf node, we have formed a complete number.
        // Return this number to be summed up.
        if (node->left == nullptr && node->right == nullptr) {
            return currentSum;
        }

        // If it's not a leaf node, continue the traversal.
        // The total sum for this subtree is the sum of numbers from left and right subtrees.
        return dfs(node->left, currentSum) + dfs(node->right, currentSum);
    }
};

Sum Root to Leaf Numbers in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function sumNumbers(root: TreeNode | null): number {
    // Helper function to perform DFS and calculate sum.
    function dfs(node: TreeNode | null, currentSum: number): number {
        // If the node is null, this path contributes nothing.
        if (!node) {
            return 0;
        }

        // Update the current sum by appending the current node's value.
        // TypeScript's number type is 64-bit float, safe from overflow here.
        currentSum = currentSum * 10 + node.val;

        // If it's a leaf node, we've found a complete number.
        if (!node.left && !node.right) {
            return currentSum;
        }

        // If it's an internal node, sum up results from children.
        return dfs(node.left, currentSum) + dfs(node.right, currentSum);
    }

    // Initial call to the recursive helper function.
    return dfs(root, 0);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.