Sum binary tree path ints

This commit is contained in:
2023-10-21 16:34:42 -04:00
parent e92d117a41
commit cee338520e
2 changed files with 45 additions and 0 deletions
+28
View File
@@ -251,3 +251,31 @@ def collect_binary_tree_levels(
yield (level, node)
yield from collect_binary_tree_levels(level + 1, node.right)
yield from collect_binary_tree_levels(level + 1, node.left)
def sum_binary_tree_path_ints(root: stdlib.Node | None) -> int:
path_ints: list[int] = []
for path in collect_binary_tree_paths(root):
path_ints.append(int("".join([str(node.val) for node in path])))
return sum(path_ints)
def collect_binary_tree_paths(
node: stdlib.Node | None,
) -> typing.Iterator[list[stdlib.Node]]:
if node is None:
return
if node.right is None and node.left is None:
yield [node]
return
if node.right is not None:
for path in collect_binary_tree_paths(node.right):
yield [node] + path
if node.left is not None:
for path in collect_binary_tree_paths(node.left):
yield [node] + path