Skip to content

Commit 9f34e05

Browse files
author
weiy
committed
sum root to leaf numbers
1 parent f126f7a commit 9f34e05

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

Tree/SumRootToLeafNumbers.py

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""
2+
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
3+
4+
An example is the root-to-leaf path 1->2->3 which represents the number 123.
5+
6+
Find the total sum of all root-to-leaf numbers.
7+
8+
Note: A leaf is a node with no children.
9+
10+
Example:
11+
12+
Input: [1,2,3]
13+
1
14+
/ \
15+
2 3
16+
Output: 25
17+
Explanation:
18+
The root-to-leaf path 1->2 represents the number 12.
19+
The root-to-leaf path 1->3 represents the number 13.
20+
Therefore, sum = 12 + 13 = 25.
21+
Example 2:
22+
23+
Input: [4,9,0,5,1]
24+
4
25+
/ \
26+
9 0
27+
/ \
28+
5 1
29+
Output: 1026
30+
Explanation:
31+
The root-to-leaf path 4->9->5 represents the number 495.
32+
The root-to-leaf path 4->9->1 represents the number 491.
33+
The root-to-leaf path 4->0 represents the number 40.
34+
Therefore, sum = 495 + 491 + 40 = 1026.
35+
36+
给一只二叉树,输出所有从根到叶路径的总和。
37+
O(n) 遍历。 字符串 -> 数字 -> 求和。
38+
39+
测试用例:
40+
https://leetcode.com/problems/sum-root-to-leaf-numbers/description/
41+
42+
24 ms beat 75%
43+
44+
"""
45+
# Definition for a binary tree node.
46+
# class TreeNode(object):
47+
# def __init__(self, x):
48+
# self.val = x
49+
# self.left = None
50+
# self.right = None
51+
52+
class Solution(object):
53+
def sumNumbers(self, root):
54+
"""
55+
:type root: TreeNode
56+
:rtype: int
57+
"""
58+
59+
result = []
60+
if not root:
61+
return 0
62+
63+
def helper(root, string):
64+
if not root.left and not root.right:
65+
result.append(int(string+str(root.val)))
66+
return
67+
68+
if root.left:
69+
helper(root.left, string+str(root.val))
70+
71+
if root.right:
72+
helper(root.right, string+str(root.val))
73+
helper(root, '')
74+
return sum(result)

0 commit comments

Comments
 (0)