Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. (树型数值之和)
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
class : defdfs(self, root): ifnot root: return left = self.dfs(root.left) right = self.dfs(root.right) ifnot left andnot right: return str(root.val) result = [] if left: for num in left: result.append(str(root.val)+str(num)) if right: for num in right: result.append(str(root.val)+str(num)) return result defsumNumbers(self, root: TreeNode) -> int: ifnot root: return0 nums = self.dfs(root) return sum(int(num) for num in nums)
近期评论