129. 求根到叶子节点数字之和
比较简单的一道深搜题,一看题的时候想到了整数溢出,但是看提交通过率挺高,应该不会卡,就没管,如果考虑溢出的话可以在递归的时候将数字转成字符串
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
if not root:
return 0
def sum_Tree(root,leave_num = 0):
sum_left = sum_right = 0
if not root.left and not root.right:
return leave_num*10 + root.val
if root.left:
sum_left = sum_Tree(root.left,leave_num*10 + root.val)
if root.right:
sum_right = sum_Tree(root.right,leave_num*10 + root.val)
return sum_left + sum_right
return sum_Tree(root)
时间复杂度O(n)