Skip to content

Instantly share code, notes, and snippets.

@viveksyngh
Created September 28, 2015 07:00
Show Gist options
  • Select an option

  • Save viveksyngh/828c3d66d8befc9d9526 to your computer and use it in GitHub Desktop.

Select an option

Save viveksyngh/828c3d66d8befc9d9526 to your computer and use it in GitHub Desktop.
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 % 1003.
__author__ = 'Vivek'
#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 % 1003.
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def helper(self, res, Sum , A) :
if A.left == None and A.right == None :
Sum = Sum * 10 + A.val
res.append(Sum)
Sum /= 10
return
Sum = Sum * 10 + A.val
#print Sum
if A.left != None :
self.helper(res, Sum, A.left)
if A.right != None :
self.helper(res, Sum, A.right)
Sum /= 10
#print Sum
def sumNumbers(self, A):
res = []
Sum = 0
self.helper(res, Sum, A)
result = 0
for r in res :
result = (result + r)%1003
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment