104. Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Thoughts
- As with a lot of tree algorithms I think the best solution here is to use a recursive algorithm to count while traversing down the tree
Solution
/**
* 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;
return Math.max(maxDepth(root.left) + 1, maxDepth(root.right) + 1);
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Conclusion
Wow. This was much easier than I was thinking it would be lmao. I forgot just how easy this was. Still good review and gets me in a tree-thinking mindset.