Skip to content

Commit a90f0fc

Browse files
authored
Merge pull request #103 from BrianLusina/feat/datastructures-binary-tree-zigzag-level-order
feat(datastructures, binary-tree): zig zag level order traversal
2 parents 3a081e7 + 773eeba commit a90f0fc

File tree

1 file changed

+52
-2
lines changed

1 file changed

+52
-2
lines changed

datastructures/trees/binary/tree/__init__.py

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import math
2-
from typing import Optional, List, Any, Generator, Dict, Iterator
2+
from typing import Optional, List, Any, Generator, Dict, Iterator, Tuple
33
from collections import defaultdict, deque
44
from itertools import chain
55

@@ -650,7 +650,7 @@ def longest_zig_zag_stack(self) -> int:
650650
return 0
651651

652652
path_length = 0
653-
stack = [(self.root, 0, None)]
653+
stack: List[Tuple[BinaryTreeNode | None, int, str | None]] = [(self.root, 0, None)]
654654

655655
while stack:
656656
node, length, last = stack.pop()
@@ -674,6 +674,56 @@ def longest_zig_zag_stack(self) -> int:
674674

675675
return path_length
676676

677+
def zig_zag_level_order(self) -> List[List[BinaryTreeNode]]:
678+
"""
679+
Perform zigzag level order traversal of a binary tree.
680+
681+
Returns:
682+
List[List[BinaryTreeNode]] - zigzag level order traversal
683+
684+
Time Complexity: O(n) where n is the number of nodes
685+
Space Complexity: O(w) where w is the maximum width of the tree
686+
"""
687+
if not self.root:
688+
return []
689+
# start by adding the root node to the result
690+
result: List[List[BinaryTreeNode]] = []
691+
692+
# traverse the tree from the root moving down level by level and adding the nodes in zig zag manner. the first
693+
# level will start with the left and then go right, the iteration will change direction on each level
694+
# we use a queue to traverse the tree level by level
695+
queue = deque([self.root])
696+
697+
# starting at zero, because the tree levels are counted from 0
698+
level_number = 0
699+
700+
while queue:
701+
level_size = len(queue)
702+
current_level = []
703+
704+
for i in range(level_size):
705+
# popleft allows FIFO behavior removing from the front
706+
node = queue.popleft()
707+
current_level.append(node)
708+
709+
# add children for next level
710+
if node.left:
711+
queue.append(node.left)
712+
if node.right:
713+
queue.append(node.right)
714+
715+
# if level number is odd reverse the list, every odd level is reversed
716+
if level_number % 2 == 1:
717+
result.append(current_level[::-1])
718+
else:
719+
# otherwise add the current level
720+
result.append(current_level)
721+
722+
# add a level and proceed
723+
level_number += 1
724+
725+
return result
726+
677727
def right_view(self) -> List[T]:
678728
"""Return a list of values representing the right view of a binary tree
679729

0 commit comments

Comments
 (0)