Skip to content

Instantly share code, notes, and snippets.

@Ray1988
Created March 6, 2014 18:56
Show Gist options
  • Save Ray1988/9396858 to your computer and use it in GitHub Desktop.
Save Ray1988/9396858 to your computer and use it in GitHub Desktop.
Sum Root to Leaf Numbers(Python)
"""
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