Saturday, February 23, 2019

LeetCode 129. Sum Root to Leaf Numbers

'''
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.

Note: A leaf is a node with no children.
'''
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def helper(i, node):
            if node:
                if not node.left and not node.right:
                    self.result += i*10+node.val
                if node.left: helper(i*10+node.val, node.left)
                if node.right: helper(i*10+node.val, node.right)
       
        self.result = 0
        helper(0, root)
        return self.result

No comments:

Post a Comment