题目来源:
https://leetcode.com/problems/sum-root-to-leaf-numbers/
题意分析:
一棵树,从跟节点到叶子节点比如1->2那么这个叶子代表12,计算所有叶子的和。
题目思路:
这题主要是怎么计算叶子的数值。leaf = node.sum * 10 + leaf.val。记录所有叶子的数值,然后相加即可。
代码(python):
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 import math 8 class Solution(object): 9 def sumNumbers(self, root): 10 """ 11 :type root: TreeNode 12 :rtype: int 13 """ 14 ans = [] 15 def solve(sum,root): 16 if root: 17 sum += root.val 18 if root.right == None and root.left == None: 19 ans.append(sum) 20 if root.right: 21 solve(sum*10,root.right) 22 if root.left: 23 solve(sum*10,root.left) 24 solve(0,root) 25 res = 0 26 for i in ans: 27 res += i 28 return res