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
Maximum Depth of Binary Tree in Python
A binary tree's maximum depth is the number of nodes along the longest path from the root to any leaf node. This is a fundamental tree traversal problem that can be solved efficiently using recursion.
Algorithm
The recursive approach works as follows ?
- If the current node is empty (None), return 0
- Otherwise, return 1 + maximum depth of left and right subtrees
- The base case handles empty nodes, while recursion explores all paths
Implementation
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert(temp, data):
queue = []
queue.append(temp)
while len(queue):
temp = queue.pop(0)
if not temp.left:
if data is not None:
temp.left = TreeNode(data)
else:
temp.left = TreeNode(0)
break
else:
queue.append(temp.left)
if not temp.right:
if data is not None:
temp.right = TreeNode(data)
else:
temp.right = TreeNode(0)
break
else:
queue.append(temp.right)
def make_tree(elements):
tree = TreeNode(elements[0])
for element in elements[1:]:
insert(tree, element)
return tree
class Solution:
def maxDepth(self, root):
if root is None:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return 1 + max(left_depth, right_depth)
# Create the tree: [1,2,2,3,4,None,3]
tree1 = make_tree([1, 2, 2, 3, 4, None, 3])
solution = Solution()
print(solution.maxDepth(tree1))
3
Alternative Iterative Approach
Using level-order traversal with a queue ?
from collections import deque
class Solution:
def maxDepthIterative(self, root):
if not root:
return 0
queue = deque([root])
depth = 0
while queue:
depth += 1
level_size = len(queue)
for _ in range(level_size):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth
# Test with the same tree
tree1 = make_tree([1, 2, 2, 3, 4, None, 3])
solution = Solution()
print(solution.maxDepthIterative(tree1))
3
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(n) | O(h) - height | Clean, readable code |
| Iterative | O(n) | O(w) - width | Avoiding recursion limits |
Conclusion
The recursive approach is more intuitive and commonly used for finding maximum depth. Both methods visit each node exactly once, making them equally efficient with O(n) time complexity.
Advertisements
