# 129. 求根到叶子节点数字之和

[https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/submissions/)

## 解法一：dfs

dfs遍历，用path记录路径，到达叶节点就将路径上的数字转成int，写入全局res

```python
class Solution:
    def sumNumbers(self, root: TreeNode) -> int:
        self.res = 0
        self.dfs(root, [])
        return self.res
    
    def dfs(self, root, path):    #path为路径上的数字列表，以字符形式存储
        if not root:    #出口，空节点
            return 
        if not root.left and not root.right:    #叶节点
            path.append(str(root.val))            
            self.res += int(''.join(path))
        #递归左右子树
        self.dfs(root.left, path+[str(root.val)])
        self.dfs(root.right, path+[str(root.val)])
```
