104. Maximum Depth of Binary Tree | LeetCode Using Python
In my latest video, I tackle the problem of finding the maximum depth of a binary tree using Python. I walk through a straightforward Breadth-First Search (BFS) approach, demonstrating how to efficiently compute the depth level by level.
Python Code:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
#Time complexity of O(n). n being nodes in the tree
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
#BFS - Breadth First Search - level by level from left to right
queue = [root] # First in first out
depth = 0
while queue:
level_size = len(queue)
for _ in range(level_size):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
depth += 1
return depth