DFS

LeetCode 129 Sum Root to Leaf Numbers (Python)

Posted by 小明MaxMing on June 26, 2020

题目

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.

解题思路

递归向下传递当前路径的数,如果是叶节点,返回这个数,否则返回两个子树和

代码

class Solution:
    def sumNumbers(self, root: TreeNode) -> int:
        def find(root, n):
            if root is None:
                return 0
            cur = n * 10 + root.val
            if root.left is None and root.right is None:
                return cur
            return find(root.left, cur) + find(root.right, cur)
        
        return find(root, 0)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅