Skip to content

Commit e028189

Browse files
1022 Sum of Root To Leaf Binary Numbers.py
1 parent 49d15b1 commit e028189

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given a binary tree, each node has value 0 or 1. Each root-to-leaf path
4+
represents a binary number starting with the most significant bit. For example,
5+
if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary,
6+
which is 13.
7+
8+
For all leaves in the tree, consider the numbers represented by the path from
9+
the root to that leaf.
10+
11+
Return the sum of these numbers.
12+
13+
Example 1:
14+
Input: [1,0,1,0,1,0,1]
15+
Output: 22
16+
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
17+
18+
Note:
19+
The number of nodes in the tree is between 1 and 1000.
20+
node.val is 0 or 1.
21+
The answer will not exceed 2^31 - 1.
22+
"""
23+
24+
25+
# Definition for a binary tree node.
26+
class TreeNode:
27+
def __init__(self, x):
28+
self.val = x
29+
self.left = None
30+
self.right = None
31+
32+
33+
class Solution:
34+
def __init__(self):
35+
self.ret = 0
36+
self.lst = []
37+
38+
def sumRootToLeaf(self, root: TreeNode) -> int:
39+
"""
40+
Brute force, keep a lst, space O(log n)
41+
Error-prone
42+
"""
43+
self.dfs(root)
44+
return self.ret
45+
46+
def dfs(self, node):
47+
if not node:
48+
return
49+
50+
self.lst.append(node.val) # error prone
51+
if not node.left and not node.right:
52+
# leaf
53+
cur = 0
54+
for a in self.lst:
55+
cur <<= 1
56+
cur += a
57+
self.ret += cur
58+
else:
59+
self.dfs(node.left)
60+
self.dfs(node.right)
61+
self.lst.pop()

0 commit comments

Comments
 (0)