104. Maximum Depth of Binary Tree | LeetCode Using Python

104. Maximum Depth of Binary Tree | LeetCode Using Python

In this video, I demonstrate how to efficiently determine the maximum depth of a binary tree using Breadth-First Search (BFS). Watch as I explain the step-by-step process and the key concepts behind the algorithm

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

Similar Posts