https://leetcode.com/problems/sum-root-to-leaf-numbers/
思路1
用dfs preorder求就行
class Solution(object):
def dfs(self, root, subres, res):
if root:
if root.left == None and root.right == None:
#print subres + str(root.val)
res[0] += int(subres + str(root.val))
else:
self.dfs(root.left, subres + str(root.val), res)
self.dfs(root.right, subres + str(root.val), res)
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
res = [0]
self.dfs(root, '', res)
return res[0]
思路2
还提供了另一种递归的办法
class Solution:
# @param root, a tree node
# @return an integer
def sum(self, root, preSum):#preSum记录root的父节点到global root的Sum。
if root==None: return 0
preSum = preSum*10 + root.val#这里跟位操作有点像,preSum向左移动一位,然后加上root.val。
if root.left==None and root.right==None: return preSum
return self.sum(root.left, preSum)+self.sum(root.right, preSum)
def sumNumbers(self, root):
return self.sum(root, 0)