Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 6 additions & 62 deletions practice/leetcode/solutions_00000/solution_00129.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,71 +18,18 @@ def sumNumbers(self, root):
:type root: TreeNode
:rtype: int
"""
acc = []

def rec(root, path, pathLen):
def rec(root, total):
if not root:
return

if len(path) > pathLen:
path[pathLen] = str(root.val)
else:
path.append(str(root.val))
return 0

pathLen += 1
total = total * 10 + root.val

if root.left is None and root.right is None:
acc.append(int(''.join(path[:pathLen])))
else:
rec(root.left, path, pathLen)
rec(root.right, path, pathLen)

path = []
rec(root, path, 0)

return sum(acc)

return total

class Solution2(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return rec(root.left, total) + rec(root.right, total)

def root_to_leaf_pathes(d, child):
q = [child]
while True:
parent = d.get(q[0])
if not parent:
break
q.insert(0, parent)

res = int(''.join([str(n.val) for n in q]))

return res

stack, parent = [root], {}
parent[root] = None
sum_ = 0

while stack:

node = stack.pop()

if node.left is None and node.right is None:
sum_ += root_to_leaf_pathes(parent, node)

if node.left:
parent[node.left] = node
stack.append(node.left)
if node.right:
parent[node.right] = node
stack.append(node.right)

return sum_
return rec(root, 0)


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

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

solution2 = Solution2()
self.assertEqual(solution2.sumNumbers(root), 1026)


if __name__ == '__main__':
unittest.main()
Loading