Trees · Easy
Maximum Depth of Binary Tree: the idea to remember.
Return the number of nodes on the longest root to leaf path.
The core insight
Depth is one plus the larger child depth; an empty tree has depth zero.
Why it works
A longest path from a nonempty root must continue through its deeper child.
The mistake to avoid
The common convention counts nodes. An empty tree is zero and a leaf is one.
Time: O(n)Space: O(h) call stack
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.