题目
思路
递归,计算出所有从根节点到叶子节点的数字,保存起来,最后相加。
代码
# 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)