Created
March 6, 2014 18:56
-
-
Save Ray1988/9396858 to your computer and use it in GitHub Desktop.
Sum Root to Leaf Numbers(Python)
This file contains 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
""" | |
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. | |
For example, | |
1 | |
/ \ | |
2 3 | |
The root-to-leaf path 1->2 represents the number 12. | |
The root-to-leaf path 1->3 represents the number 13. | |
Return the sum = 12 + 13 = 25. | |
""" | |
# Definition for a binary tree node | |
# class TreeNode: | |
# def __init__(self, x): | |
# self.val = x | |
# self.left = None | |
# self.right = None | |
class Solution: | |
# @param root, a tree node | |
# @return an integer | |
def sumNumbers(self, root): | |
if not root: | |
return 0 | |
current=0 | |
sum=[0] | |
self.calSum(root, current, sum) | |
return sum[0] | |
def calSum(self, root, current, sum): | |
if not root: | |
return | |
current=current*10+root.val | |
if not root.left and not root.right: | |
sum[0]+=current | |
return | |
self.calSum(root.left, current, sum) | |
self.calSum(root.right,current, sum) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment