原题
https://leetcode.cn/problems/sum-root-to-leaf-numbers/description/
思路
深度优先搜索
复杂度
时间:O(n)
空间:O(n)
Python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
ans = 0
def dfs(root, path):
nonlocal ans
if not root:
return
path += str(root.val)
# 叶子节点就返回
if root.left is None and root.right is None:
ans += int(path)
return
dfs(root.left, path)
dfs(root.right, path)
dfs(root, '')
return ans
Go代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumNumbers(root *TreeNode) int {
ans := 0
var dfs func(*TreeNode, string)
dfs = func(root *TreeNode, path string) {
if root == nil {
return
}
path += string(root.Val + '0')
// 遇到叶子节点就更新结果并返回
if root.Left == nil && root.Right == nil {
i, err := strconv.Atoi(path)
if err != nil {
panic(err)
}
ans += i
return
}
dfs(root.Left, path)
dfs(root.Right, path)
}
dfs(root, "")
return ans
}
148

被折叠的 条评论
为什么被折叠?



