Blind 75 - Maximum Depth of Binary Tree
go to each depth, incrementing a depth counter by 1. return max of it.
[Video]
Find the maximum depth of the binary tree.
Approaches
O(n) time. O(1) space. 10 lines.
go to each depth, incrementing a depth counter by 1. return max of it.
public int maxDepth(TreeNode root, int depth){
if(root == null){
return depth;
}
int nextDepth = depth+1;
return Math.max(maxDepth(root.left, nextDepth), maxDepth(root.right,nextDepth));
}
public int maxDepth(TreeNode root) {
return maxDepth(root, 0);
}
Code optimization: No need to create a separate function;
Optimized: 5 lines
Source: Java 100% Faster Very Simple - LeetCode Discuss
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
}