Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to traverse binary tree level wise in alternating way in Python
Suppose we have a binary tree, we need to traverse it level by level in an alternating manner − first level left−to−right, second level right−to−left, third level left−to−right, and so on.
So, if the input is like:
Then the output will be [5, -10, 4, -2, -7, 15]
Algorithm
To solve this problem, we use two stacks to alternate between left−to−right and right−to−left traversal ?
Use two stacks:
s1for current level,s2for next levelFor left−to−right: push left child first, then right child
For right−to−left: push right child first, then left child
Alternate between the two stacks until both are empty
Implementation
class TreeNode:
def __init__(self, data, left=None, right=None):
self.val = data
self.left = left
self.right = right
class Solution:
def solve(self, root):
if not root:
return []
s1 = [root] # Stack for current level
s2 = [] # Stack for next level
res = [] # Result list
while s1 or s2:
# Process left-to-right (using s1)
while s1:
node = s1.pop()
res.append(node.val)
# Add children to s2 (left first for right-to-left next)
if node.left:
s2.append(node.left)
if node.right:
s2.append(node.right)
# Process right-to-left (using s2)
while s2:
node = s2.pop()
res.append(node.val)
# Add children to s1 (right first for left-to-right next)
if node.right:
s1.append(node.right)
if node.left:
s1.append(node.left)
return res
# Create the binary tree
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(-10)
root.left.left = TreeNode(-2)
root.right.left = TreeNode(-7)
root.right.right = TreeNode(15)
# Solve and print result
ob = Solution()
result = ob.solve(root)
print(result)
[5, -10, 4, -2, -7, 15]
How It Works
The algorithm works by maintaining two stacks and alternating their usage ?
Level 0: Start with root (5) in s1, process left−to−right
Level 1: Add children to s2: left (4), right (-10). Process right−to−left: -10, 4
Level 2: Add children to s1: right first, then left. Process left−to−right: -2, -7, 15
Time and Space Complexity
Time Complexity: O(n) where n is the number of nodes
Space Complexity: O(w) where w is the maximum width of the tree
Conclusion
This zigzag level order traversal uses two stacks to alternate direction at each level. The key insight is controlling the order of child insertion to achieve the desired alternating pattern.
