【DFS】129. 求根节点到叶子结点的和
链接
https://leetcode.cn/problems/sum-root-to-leaf-numbers/description/
思路
时刻记住,DFS是递归的一种。而解决递归,最朴素的思路就是:递归的定义就是递归的解。
题目要求我们求根节点到叶子结点的和,我们要提供一个值保持其状态,退出条件直接用题目给的限定即可。
代码
# 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) -> int: res = 0 def dfs(node, cur): nonlocal res if node is None: return if node.left is None and node.right is None: res += cur * 10 + node.val dfs(node.left, cur * 10 + node.val) dfs(node.right, cur * 10 + node.val) dfs(root, 0) return res