-
Notifications
You must be signed in to change notification settings - Fork 161
/
sum-root-to-leaf-numbers.md
36 lines (29 loc) · 1.2 KB
/
sum-root-to-leaf-numbers.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<p>Given a binary tree containing digits from <code>0-9</code> only, each root-to-leaf path could represent a number.</p>
<p>An example is the root-to-leaf path <code>1->2->3</code> which represents the number <code>123</code>.</p>
<p>Find the total sum of all root-to-leaf numbers.</p>
<p><strong>Note:</strong> A leaf is a node with no children.</p>
<p><strong>Example:</strong></p>
<pre>
<strong>Input:</strong> [1,2,3]
1
/ \
2 3
<strong>Output:</strong> 25
<strong>Explanation:</strong>
The root-to-leaf path <code>1->2</code> represents the number <code>12</code>.
The root-to-leaf path <code>1->3</code> represents the number <code>13</code>.
Therefore, sum = 12 + 13 = <code>25</code>.</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
<strong>Output:</strong> 1026
<strong>Explanation:</strong>
The root-to-leaf path <code>4->9->5</code> represents the number 495.
The root-to-leaf path <code>4->9->1</code> represents the number 491.
The root-to-leaf path <code>4->0</code> represents the number 40.
Therefore, sum = 495 + 491 + 40 = <code>1026</code>.</pre>