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

Function zigzag

data_structures/binary_tree/binary_tree_traversals.py:163–182  ·  view source on GitHub ↗

ZigZag traverse: Returns a list of nodes value from left to right and right to left, alternatively. >>> list(zigzag(make_tree())) [1, 3, 2, 4, 5]

(root: Node | None)

Source from the content-addressed store, hash-verified

161
162
163def zigzag(root: Node | None) -> Generator[int]:
164 """
165 ZigZag traverse:
166 Returns a list of nodes value from left to right and right to left, alternatively.
167 >>> list(zigzag(make_tree()))
168 [1, 3, 2, 4, 5]
169 """
170 if root is None:
171 return
172
173 flag = 0
174 height_tree = height(root)
175
176 for h in range(1, height_tree + 1):
177 if not flag:
178 yield from get_nodes_from_left_to_right(root, h)
179 flag = 1
180 else:
181 yield from get_nodes_from_right_to_left(root, h)
182 flag = 0
183
184
185def main() -> None: # Main function for testing.

Callers 1

mainFunction · 0.85

Calls 3

heightFunction · 0.85

Tested by

no test coverage detected