Leetcode每日一题2021/01/27

Leetcode每日一题2021/01/27_第1张图片
Leetcode每日一题2021/01/27_第2张图片

# 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
# DFS
class Solution:
    def sumNumbers(self, root: TreeNode) -> int:
        def DFS(root, preTotal):
            if not root:
                return 0
            total = preTotal*10 + root.val	# 这个是核心
            if(not root.left and not root.right):
                return total
            return DFS(root.left, total) + DFS(root.right, total)
        return DFS(root, 0)

Leetcode每日一题2021/01/27_第3张图片

你可能感兴趣的:(Leetcode,dfs,leetcode,算法,二叉树)