File tree Expand file tree Collapse file tree 1 file changed +10
-6
lines changed Expand file tree Collapse file tree 1 file changed +10
-6
lines changed Original file line number Diff line number Diff line change 4
4
5
5
from collections import deque
6
6
7
- from src .classes import ListNode , TreeNode
7
+ from src .classes import ListNode , T , TreeNode
8
8
9
9
10
10
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
101
101
return node
102
102
103
103
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 ]:
105
105
"""
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.
108
109
109
110
Breadth-first order always attempts to visit the node closest to the root
110
111
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]:
113
114
if not root :
114
115
return []
115
116
116
- l : list [int ] = []
117
+ l : list [TreeNode | T ] = []
117
118
q : deque [TreeNode ] = deque ([root ])
118
119
119
120
while q :
120
121
curr : TreeNode = q .popleft ()
121
- l .append (curr .val )
122
+ if values_only :
123
+ l .append (curr .val )
124
+ else :
125
+ l .append (curr )
122
126
if curr .left :
123
127
q .append (curr .left )
124
128
if curr .right :
You can’t perform that action at this time.
0 commit comments