ยท 1 min read
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;
}Related posts
- Blind 75 - Invert Binary Tree Nov 16, 2022
- Blind 75 - Merge Two-Sorted Lists Nov 16, 2022
- Blind 75 - Subtree of Another Tree Nov 16, 2022
Get new posts by email
No spam. Unsubscribe anytime. Or grab the RSS feed.
Mailto-based for now. ButtonDown / ConvertKit can replace this form later.