难度:中等
题目描述:
思路总结:
题解一:(递归)
# 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
res = 0
def helper(node, cur_val):
if not node.left and not node.right:
nonlocal res
res += int(cur_val)
if node.left:
helper(node.left, cur_val + str(node.left.val))
if node.right:
helper(node.right, cur_val + str(node.right.val))
helper(root, str(root.val))
return res
题解一结果:
题解二:(迭代)
# 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
stack = [(root,str(root.val))]
res = 0
while stack:
cur,sumv = stack.pop()
if not cur.left and not cur.right:
res += int(sumv)
if cur.left:
stack.append((cur.left, sumv+str(cur.left.val)))
if cur.right:
stack.append((cur.right, sumv+str(cur.right.val)))
return res
题解二结果: