Skip to content

Commit 112c419

Browse files
authored
Optimize sum root to leaf numbers (#76)
1 parent 0d09194 commit 112c419

1 file changed

Lines changed: 6 additions & 62 deletions

File tree

practice/leetcode/solutions_00000/solution_00129.py

Lines changed: 6 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -18,71 +18,18 @@ def sumNumbers(self, root):
1818
:type root: TreeNode
1919
:rtype: int
2020
"""
21-
acc = []
22-
23-
def rec(root, path, pathLen):
21+
def rec(root, total):
2422
if not root:
25-
return
26-
27-
if len(path) > pathLen:
28-
path[pathLen] = str(root.val)
29-
else:
30-
path.append(str(root.val))
23+
return 0
3124

32-
pathLen += 1
25+
total = total * 10 + root.val
3326

3427
if root.left is None and root.right is None:
35-
acc.append(int(''.join(path[:pathLen])))
36-
else:
37-
rec(root.left, path, pathLen)
38-
rec(root.right, path, pathLen)
39-
40-
path = []
41-
rec(root, path, 0)
42-
43-
return sum(acc)
44-
28+
return total
4529

46-
class Solution2(object):
47-
def sumNumbers(self, root):
48-
"""
49-
:type root: TreeNode
50-
:rtype: int
51-
"""
52-
if not root:
53-
return 0
30+
return rec(root.left, total) + rec(root.right, total)
5431

55-
def root_to_leaf_pathes(d, child):
56-
q = [child]
57-
while True:
58-
parent = d.get(q[0])
59-
if not parent:
60-
break
61-
q.insert(0, parent)
62-
63-
res = int(''.join([str(n.val) for n in q]))
64-
65-
return res
66-
67-
stack, parent = [root], {}
68-
parent[root] = None
69-
sum_ = 0
70-
71-
while stack:
72-
73-
node = stack.pop()
74-
75-
if node.left is None and node.right is None:
76-
sum_ += root_to_leaf_pathes(parent, node)
77-
78-
if node.left:
79-
parent[node.left] = node
80-
stack.append(node.left)
81-
if node.right:
82-
parent[node.right] = node
83-
stack.append(node.right)
84-
85-
return sum_
32+
return rec(root, 0)
8633

8734

8835
class TestSolution(unittest.TestCase):
@@ -98,9 +45,6 @@ def test_sumNumbers(self):
9845

9946
self.assertEqual(solution.sumNumbers(root), 1026)
10047

101-
solution2 = Solution2()
102-
self.assertEqual(solution2.sumNumbers(root), 1026)
103-
10448

10549
if __name__ == '__main__':
10650
unittest.main()

0 commit comments

Comments
 (0)