LeetCode 129. Sum Root to Leaf Numbers

时间:2021-08-25 15:57:26

题目

LeetCode 129. Sum Root to Leaf Numbers

思路

递归,计算出所有从根节点到叶子节点的数字,保存起来,最后相加。

代码

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
    def __init__(self):
        self.num_list = []
    def findNums(self, root, num):
        if not root: return
        if not root.left and not root.right:
            self.num_list.append(num * 10 + root.val)
        else:
            if root.left:
                self.findNums(root.left, num * 10 + root.val)
            if root.right:
                self.findNums(root.right, num * 10 + root.val)
    def sumNumbers(self, root):
        """ :type root: TreeNode :rtype: int """
        self.findNums(root, 0)
        return sum(self.num_list)