Back to solutions
Maximum Depth of Binary Tree
EasyBinary TreesReturn the maximum depth, the number of nodes along the longest path from the root to a leaf.
Constraints
- 0 <= nodes <= 10^4
- -100 <= Node.val <= 100
Recursive height
Time O(n)Space O(h)
The depth of a node is one plus the larger of its children's depths. An empty subtree has depth zero.
struct TreeNode { int val; TreeNode* left; TreeNode* right; };
int maxDepth(TreeNode* root) {
if (!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}