Binary Tree Maximum Depth Problem Solution

Day - 88 Maximum Depth of Binary Tree The problem - Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Brute Force - Use level-order traversal (BFS) to visit all nodes level by level, counting the number of levels. This gives O(n) time and O(w) space where w = maximum width, which works but is more complex than needed. Approach Used - •) If root == null, return 0 (empty tree has depth 0). •) Calculate left subtree depth: left = maxDepth(root.left). •) Calculate right subtree depth: right = maxDepth(root.right). •) Return 1 + Math.max(left, right), 1 accounts for current node and Math.max(left, right) selects the deeper subtree. Complexity - Time - O(n), where n = number of nodes. Space - O(h), where h = height of tree. Note - The maximum depth of a binary tree is determined recursively: it's 1 (for the current node) plus the maximum depth of its left and right subtrees. The base case returns 0 for null nodes. This elegant recursive solution naturally follows the tree structure and computes depth in a single pass. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories