# 129 Sum Root to Leaf Numbers

## 129. Sum Root to Leaf Numbers

## 1. Question

Given a binary tree containing digits from`0-9`only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path`1->2->3`which represents the number`123`.

Find the total sum of all root-to-leaf numbers.

For example,

```
    1
   / \
  2   3
```

The root-to-leaf path`1->2`represents the number`12`.\
The root-to-leaf path`1->3`represents the number`13`.

Return the sum = 12 + 13 =`25`.

## 2. Implementation

**(1) DFS recursion**

```java
class Solution {
    public int sumNumbers(TreeNode root) {
        return findSum(root, 0);
    }

    public int findSum(TreeNode node, int sum) {
        if (node == null) {
            return 0;
        }

        sum = 10 * sum + node.val;
        if (node.left == null && node.right == null) {
            return sum;
        }

        return findSum(node.left, sum) + findSum(node.right, sum);
    }
}
```

**(2) BFS**

```java
class Solution {
    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }

        int res = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        Queue<Integer> sum = new LinkedList<>();
        queue.add(root);
        sum.add(root.val);

        while (!queue.isEmpty()) {
            TreeNode curNode = queue.remove();
            int curSum = sum.remove();

            if (curNode.left == null && curNode.right == null) {
                res += curSum;
            }

            if (curNode.left != null) {
                queue.add(curNode.left);
                sum.add(10 * curSum + curNode.left.val);
            }

            if (curNode.right != null) {
                queue.add(curNode.right);
                sum.add(10 * curSum + curNode.right.val);
            }
        }
        return res;
    }
}
```

## 3. Time & Space Complexity

DFS recursion: 时间复杂度: O(n), 空间复杂度: O(n)

BFS: 时间复杂度: O(n), 空间复杂度: O(w), w是树里有最多node的一层的node个数


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/my-algorithm-summary/data-structure/tree/129-sum-root-to-leaf-numbers.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
