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 find the maximum width of a binary tree in Python
The maximum width of a binary tree is the number of nodes that can fit between the leftmost and rightmost nodes at any level. This includes null nodes that could exist in between.
Approach
We'll use a depth-first search (DFS) approach where each node is assigned a position index. For any node at position pos, its left child gets position 2*pos and right child gets 2*pos+1. At each level, we track the minimum and maximum positions to calculate the width.
Algorithm Steps
Create a dictionary to store minimum and maximum positions for each depth level
Use DFS to traverse the tree and assign positions to each node
Track the leftmost and rightmost positions at each level
Calculate width as
rightmost - leftmost + 1for each levelReturn the maximum width found
Implementation
from collections import defaultdict
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
class Solution:
def solve(self, root):
# Dictionary to store [min_pos, max_pos] for each depth
d = defaultdict(lambda: [float('inf'), 0])
def dfs(node, pos=0, depth=0):
if not node:
return
# Update min and max positions for current depth
d[depth][0] = min(d[depth][0], pos)
d[depth][1] = max(d[depth][1], pos)
# Recursively process left and right children
dfs(node.left, 2 * pos, depth + 1)
dfs(node.right, 2 * pos + 1, depth + 1)
dfs(root)
# Find maximum width across all levels
max_width = 0
for interval in d.values():
left, right = interval
max_width = max(max_width, right - left + 1)
return max_width
# Create the binary tree
ob = Solution()
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(9)
root.right.left = TreeNode(7)
root.right.right = TreeNode(10)
root.right.left.left = TreeNode(6)
root.right.left.right = TreeNode(8)
print("Maximum width of the binary tree:", ob.solve(root))
Maximum width of the binary tree: 2
How It Works
For the given tree structure:
Level 0: Node 5 at position 0 ? width = 1
Level 1: Nodes 1,9 at positions 0,1 ? width = 2
Level 2: Nodes 7,10 at positions 2,3 ? width = 2
Level 3: Nodes 6,8 at positions 4,5 ? width = 2
The maximum width is 2, which occurs at levels 1, 2, and 3.
Time and Space Complexity
Time Complexity: O(n) where n is the number of nodes, as we visit each node once
Space Complexity: O(h) where h is the height of the tree, for the recursion stack and dictionary storage
Conclusion
This solution efficiently finds the maximum width by assigning position indices to nodes and tracking the span at each level. The DFS approach ensures we visit all nodes while maintaining the positional relationship between parent and child nodes.
