> For the complete documentation index, see [llms.txt](https://code-snippets.hbamithkumara.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://code-snippets.hbamithkumara.com/leetcode/problems/101-200/maximum-depth-of-binary-tree.md).

# 104. Maximum Depth of Binary Tree

### Description

Given a binary tree, find 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.

**Note:** A leaf is a node with no children.

### Constraints

### Approach

### Links

* [GeeksforGeeks](https://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/)
* [Leetcode](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
* [ProgramCreek](https://www.programcreek.com/2014/05/leetcode-maximum-depth-of-binary-tree-java/)
* YouTube

### **Examples**

{% tabs %}
{% tab title="Example 1" %}
**Input:** \[3, 9, 20, null, null, 15, 7]

<div align="left"><img src="/files/-MFuDgT5eTdzMmMy_aDu" alt=""></div>

**Output:** 3
{% endtab %}
{% endtabs %}

### **Solutions**

{% tabs %}
{% tab title="TreeNode" %}

```java
// Definition for a binary tree node.
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    
    TreeNode() {}
    
    TreeNode(int val) { this.val = val; }
    
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
```

{% endtab %}

{% tab title="Solution 1" %}

```java
/**
 * Time complexity : O(N)
 * Space complexity : O(log(N))
 */

class Solution {
    public int maxDepth(TreeNode root) {
        int depth = 0;
        if(root == null) return depth;
        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);
        while(!queue.isEmpty()) {
            depth++;
            int noOfNodes = queue.size();
            for(int i = 0; i < noOfNodes; i++) {
                TreeNode node = queue.poll();
                if(node.left != null) {
                    queue.add(node.left);
                }
                if(node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return depth;
    }
}
```

{% endtab %}

{% tab title="Solution 2" %}

```java
/**
 * Time complexity : O(N)
 * Space complexity : O(log(N))
 */

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int leftDepth = 1 + maxDepth(root.left);
        int rightDepth = 1 + maxDepth(root.right);
        return (leftDepth > rightDepth)? leftDepth: rightDepth;
    }
}
```

{% endtab %}
{% endtabs %}

### **Follow up**

* Sum of nodes at maximum depth of a Binary Tree - [GFG](https://www.geeksforgeeks.org/sum-nodes-maximum-depth-binary-tree/)
