> For the complete documentation index, see [llms.txt](https://liuxue2010.gitbook.io/data-structure-and-algorithms/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://liuxue2010.gitbook.io/data-structure-and-algorithms/binary-tree-and-divide-conquer/sum-root-to-leaf-numbers.md).

# Sum Root to Leaf Numbers

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

Solution:

a这道题一开始，我使用了分治，但是这道题很明显就是traverse的题目，后来我有用了resule, level模式，level为running 的变量，其实也没有必要，因为如果是数值类型的，递归可以一层层传递的，没有必要简单复杂化。

```
class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0

        self.result = 0
        self.traverse(root, 0)

        return self.result

    def traverse(self, root, curr):
        if root == None:
            return
        curr = root.val + curr * 10

        if root.left == None and root.right == None:
            self.result += curr

        if root.left:
            self.traverse(root.left, curr)
        if root.right:
            self.traverse(root.right, curr)
```
