Skip to content
AI360Xpert
Back to Trees
Easy

Maximum Depth of Binary Tree

Given the `root` of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Examples

Input:root = [3,9,20,null,null,15,7]
Output:3
Input:root = [1,null,2]
Output:2

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • -100 <= Node.val <= 100

Approach

The maximum depth of a tree is 1 plus the maximum depth of its left and right subtrees. The base case is an empty tree (null root), which has a depth of 0. Recursively calculate the max depth of the left and right children, take the maximum of the two, and add 1 for the current node.

Complexity Analysis

Time Complexity
O(n)
Space Complexity
O(h)

This is the most concise and intuitive approach.

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