Maximum Depth of Binary Tree
Find the number of nodes on the longest root-to-leaf path of a binary tree.
Work through the cases
3 examplesInput notation
A binary tree in level order on one line, using null for missing children. Omit trailing nulls; use null for an empty tree.Expected result
The maximum depth; an empty tree has depth 0.Case 1
Input
1 2 3 4
Expected output
3
Case 2
Input
null
Expected output
0
Case 3
Input
7
Expected output
1
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Depth is the number of nodes on the longest root-to-leaf path. Level-order counting of layers works, and n ≤ 10^4 is fine. A tree is recursive: the depth is one plus the larger of the two subtree depths, and the empty tree has depth 0. Recurse on both children and take the max.
Recursively traverse the left and right subtrees, calculate the maximum depth of the left and right subtrees, and then take the maximum value plus 1.
The time complexity is O(n), where n is the number of nodes in the binary tree. Each node is traversed only once in the recursion.
/**
* 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;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int l = maxDepth(root.left);
int r = maxDepth(root.right);
return 1 + Math.max(l, r);
}
}Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.
Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.