NOTE

Sum Root to Leaf Numbers

LeetCode notes on summing all numbers formed by root-to-leaf paths.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Given the root root of a binary tree, each node stores a digit from 0 to 9. Each root-to-leaf path represents a number:

For example, the path 1 -> 2 -> 3 represents the number 123. Calculate the sum of all numbers generated by root-to-leaf paths.

A leaf node is a node with no children.

2. Approach

3. Implementation

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumNumbers(root *TreeNode) int {
    sum := 0
    sumNumbersDFS(root, 0, &sum)
    return sum
}

func sumNumbersDFS(root *TreeNode, num int, sum *int) {
    if root == nil {return}
    num = num * 10 + root.Val
    if root.Left == nil && root.Right == nil {
        *sum += num
    }
    sumNumbersDFS(root.Left, num, sum)
    sumNumbersDFS(root.Right, num, sum)
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub