Sum Root to Leaf Numbers

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

The root-to-leaf path1->2represents the number12. The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

Solution:

a这道题一开始,我使用了分治,但是这道题很明显就是traverse的题目,后来我有用了resule, level模式,level为running 的变量,其实也没有必要,因为如果是数值类型的,递归可以一层层传递的,没有必要简单复杂化。

class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0

        self.result = 0
        self.traverse(root, 0)

        return self.result

    def traverse(self, root, curr):
        if root == None:
            return
        curr = root.val + curr * 10

        if root.left == None and root.right == None:
            self.result += curr

        if root.left:
            self.traverse(root.left, curr)
        if root.right:
            self.traverse(root.right, curr)

Last updated

Was this helpful?