LeetCode 104: Maximum Depth of Binary Tree Solution

Master LeetCode problem 104 (Maximum Depth of Binary Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

104. Maximum Depth of Binary Tree

Problem Explanation

Explanation

To find the maximum depth of a binary tree, we can use a depth-first search (DFS) approach. We will recursively traverse the tree, calculating the depth at each node. The maximum depth of the tree is the maximum of the depths of the left and right subtrees, plus 1 for the current node.

Algorithm:

  1. If the root is null, return 0 as the depth.
  2. Recursively calculate the maximum depth of the left subtree.
  3. Recursively calculate the maximum depth of the right subtree.
  4. Return the maximum of the depths of the left and right subtrees, plus 1 for the current node.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree. We visit each node exactly once.

Space Complexity:

The space complexity is O(h), where h is the height of the binary tree. In the worst case, the space complexity is O(n) for a skewed tree, and in the best case, it is O(log n) for a balanced tree.

Solution Code

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 104 (Maximum Depth of Binary Tree)?

This page provides optimized solutions for LeetCode problem 104 (Maximum Depth of Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 104 (Maximum Depth of Binary Tree)?

The time complexity for LeetCode 104 (Maximum Depth of Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 104 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 104 in Java, C++, or Python.

Back to LeetCode Solutions