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
Selected Reading
Binary Tree Inorder Traversal in Python
Binary tree inorder traversal visits nodes in the order: left subtree, root, right subtree. This article demonstrates how to perform inorder traversal iteratively using a stack instead of recursion.
Algorithm Steps
The iterative approach uses a stack to simulate the recursive call stack ?
- Initialize an empty result array and stack
- Start with current node as root
- While current is not null, push it to stack and move to left child
- When no left child exists, pop from stack, add to result, and move to right child
- Repeat until stack is empty
Implementation
TreeNode Class
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def create_tree():
# Creating the tree: 10, 5, 15, 2, 7, None, 20
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(2)
root.left.right = TreeNode(7)
root.right.right = TreeNode(20)
return root
Iterative Inorder Traversal
def inorder_traversal(root):
result = []
stack = []
current = root
while True:
# Go to the leftmost node
while current:
stack.append(current)
current = current.left
# If stack is empty, we're done
if len(stack) == 0:
return result
# Pop and process the node
node = stack.pop()
result.append(node.data)
# Move to right subtree
current = node.right
return result
# Test the implementation
root = create_tree()
print("Inorder traversal:", inorder_traversal(root))
Inorder traversal: [2, 5, 7, 10, 15, 20]
How It Works
The algorithm follows these steps for the example tree ?
- Start at root (10): Push 10, move to left child (5)
- At node 5: Push 5, move to left child (2)
- At node 2: Push 2, move to left child (None)
- Left is None: Pop 2, add to result [2], move to right (None)
- Right is None: Pop 5, add to result [2, 5], move to right (7)
- At node 7: Push 7, move to left (None)
- Left is None: Pop 7, add to result [2, 5, 7], move to right (None)
- Continue this process until all nodes are processed
Space and Time Complexity
| Aspect | Recursive | Iterative |
|---|---|---|
| Time Complexity | O(n) | O(n) |
| Space Complexity | O(h) call stack | O(h) explicit stack |
| Stack Overflow Risk | Yes (deep trees) | No |
Where n is the number of nodes and h is the height of the tree.
Conclusion
Iterative inorder traversal uses an explicit stack to avoid recursion, making it safer for deep trees. The algorithm visits nodes in left-root-right order, producing a sorted sequence for binary search trees.
Advertisements
