MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / level_order

Function level_order

data_structures/binary_tree/binary_tree_traversals.py:96–116  ·  view source on GitHub ↗

Returns a list of nodes value from a whole binary tree in Level Order Traverse. Level Order traverse: Visit nodes of the tree level-by-level. >>> list(level_order(make_tree())) [1, 2, 3, 4, 5]

(root: Node | None)

Source from the content-addressed store, hash-verified

94
95
96def level_order(root: Node | None) -> Generator[int]:
97 """
98 Returns a list of nodes value from a whole binary tree in Level Order Traverse.
99 Level Order traverse: Visit nodes of the tree level-by-level.
100 >>> list(level_order(make_tree()))
101 [1, 2, 3, 4, 5]
102 """
103
104 if root is None:
105 return
106
107 process_queue = deque([root])
108
109 while process_queue:
110 node = process_queue.popleft()
111 yield node.data
112
113 if node.left:
114 process_queue.append(node.left)
115 if node.right:
116 process_queue.append(node.right)
117
118
119def get_nodes_from_left_to_right(root: Node | None, level: int) -> Generator[int]:

Callers 1

mainFunction · 0.70

Calls 2

popleftMethod · 0.80
appendMethod · 0.45

Tested by

no test coverage detected