EMChamp Blog

Coding Problem 7 | Maximum Depth of Binary Tree

One particular problem from leetcode asks you to find the maximum depth of a binary tree https://leetcode.com/problems/maximum-depth-of-binary-tree/ . Like linked list, I usually trace edge cases first when going through Binary Search Tree problems. Here are the edge cases I considered:

1) Case where BST is empty

This is simple just return 0 since there is no depth

2) Case where BST has one node or node is last element

If both node.left and node.right are empty that means this is the last node so the depth is (however many nodes it took to get here)+1.

3) Case where node has one or more children

1
2
3
4
5
6
7
8
9
10
11
12
13

public class Solution {
public int maxDepth(TreeNode root) {
if(root==null)
return 0;

if(root.left != null || root.right != null)
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
else
return 1;
}
}