Algo-Sim › Binary Trees & BST
Maximum Depth of Binary Tree
Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input
A node's depth is 1 plus the deeper of its two subtrees; an empty tree has depth 0.
Problem
Return the maximum depth of a binary tree: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0.
Constraints
- 0 ≤ number of nodes ≤ 10⁴
- -100 ≤ Node.val ≤ 100
Edge cases to test
- Empty tree:
0 - One node:
1 - A long chain (recursion depth)
Follow-up questions
- What is the minimum depth?
- The nearest leaf: BFS stops at the first leaf. A node with one child is not a leaf, which trips up
min(left, right) + 1(LC 111). - How do you avoid recursion?
- Level-order BFS counting levels: O(n) time and O(width) space.
Solution
Java
public int maxDepth(TreeNode root) {
if (root == null) return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return 1 + Math.max(left, right);
}Python
def max_depth(root):
if not root:
return 0
left = max_depth(root.left)
right = max_depth(root.right)
return 1 + max(left, right)C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxDepth(TreeNode *root) {
if (root == nullptr)
return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return 1 + std::max(left, right);
}
};
More Binary Trees & BST problems
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Construct Binary Tree from Preorder and Inorder Traversal (Medium)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)