Created
September 28, 2015 07:00
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| __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