Max Depth of Binary Tree
Maximum Depth of Binary Tree (LC.104)
Given a binary tree, find its maximum depth.
Example
+ 1
/ \
2 3
/ \
4 5
Max depth: 3Analysis
If you can do D&C, always try D&C first. Traverse is longer to write.
Code
public int maxDepth(TreeNode root) {
// base case
if (root == null)
return 0;
// divide
int leftSubtree = maxDepth(root.left);
int rightSubtree = maxDepth(root.right);
// conquer
return 1 + Math.max(leftSubtree, rightSubtree);
}Minimum Depth of Binary Tree (LC.111)
Given a binary tree, find its minimum depth.
Example
Analysis
Divide and conquer again. But this time need to handle a special case where a subtree has a left child but no right child. Math.min(leftSubtree, rightSubtree) will give 0 but in truth we have 1.
Code
Last updated