# 求根节点到叶节点数字之和

题目链接: <https://leetcode.cn/problems/sum-root-to-leaf-numbers>

## 解题思路：

1. 深度遍历，计算出叶子节点的值，将叶子节点值计算入和

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

func sum(root *TreeNode, lastNum int) int {
	if root == nil {
		return 0
	}
	if root.Left == nil && root.Right == nil {
		return lastNum*10 + root.Val
	}
	levelVal := lastNum*10 + root.Val
	num := sum(root.Left, levelVal) + sum(root.Right, levelVal)
	return num
}
```

## 复杂度分析

* **时间复杂度：** 时间复杂度为$$O(n)$$
* **空间复杂度：** 空间复杂度为$$O(n)$$。


---

# 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://leetcodebook-1.gitbook.io/top-interview-150/tree/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.
