您的位置:首页 > 其它

leetcode -- Sum Root to Leaf Numbers -- dfs

2015-12-17 13:44 316 查看
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

/article/4982526.html还提供了另一种递归的办法

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: