Skip to content

Commit 05d797a

Browse files
Extend create_bfs_list_from_binary_tree()
1 parent 1b976b0 commit 05d797a

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

tests/utils.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from collections import deque
66

7-
from src.classes import ListNode, TreeNode
7+
from src.classes import ListNode, T, TreeNode
88

99

1010
def create_linked_list_from_list(l: list[int]) -> ListNode | None:
@@ -101,10 +101,11 @@ def _create_binary_tree_from_list(l: list[int | None], i: int) -> TreeNode | Non
101101
return node
102102

103103

104-
def create_bfs_list_from_binary_tree(root: TreeNode | None) -> list[int]:
104+
def create_bfs_list_from_binary_tree(*, root: TreeNode | None, values_only: bool = True) -> list[TreeNode | T]:
105105
"""
106-
Creates a list of integers in breadth-first search order given the root
107-
node of a binary tree.
106+
Creates a list of nodes in breadth-first search order given the root node
107+
of a binary tree. If values_only is False, the list contains the TreeNode
108+
objects themselves.
108109
109110
Breadth-first order always attempts to visit the node closest to the root
110111
that it has not already visited. This is also called a level-order
@@ -113,12 +114,15 @@ def create_bfs_list_from_binary_tree(root: TreeNode | None) -> list[int]:
113114
if not root:
114115
return []
115116

116-
l: list[int] = []
117+
l: list[TreeNode | T] = []
117118
q: deque[TreeNode] = deque([root])
118119

119120
while q:
120121
curr: TreeNode = q.popleft()
121-
l.append(curr.val)
122+
if values_only:
123+
l.append(curr.val)
124+
else:
125+
l.append(curr)
122126
if curr.left:
123127
q.append(curr.left)
124128
if curr.right:

0 commit comments

Comments
 (0)