[GeeksForGeeks] Find Minimum Depth of a Binary Tree
Give a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from root node down to the nearest leaf node.
Solution 1. Recursion
1 public class MinDepthBt { 2 public int getMinDepth(TreeNode root) { 3 return helper(root, 0); 4 } 5 private int helper(TreeNode node, int depth) { 6 if(node == null) { 7 return depth; 8 } 9 return Math.min(helper(node.left, depth + 1), helper(node.right, depth + 1)); 10 } 11 }
Solution 2. Level order traversal, found the first leaf node and return its level.
This solution is better than the recursive solution because we don't need to traverse all nodes.
1 import java.util.LinkedList; 2 import java.util.Queue; 3 4 public class MinDepthBt { 5 public int getMinDepth(TreeNode root) { 6 if(root == null) { 7 return 0; 8 } 9 if(root.left == null || root.right == null) { 10 return 1; 11 } 12 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 13 queue.add(root); 14 int currLevel = 1; int minLevel = 1; 15 boolean minDepthFound = false; 16 while(!minDepthFound && !queue.isEmpty()) { 17 int size = queue.size(); 18 for(int i = 0; i < size; i++) { 19 TreeNode curr = queue.poll(); 20 if(curr.left == null && curr.right == null) { 21 minDepthFound = true; 22 minLevel = currLevel; 23 break; 24 } 25 if(curr.left != null) { 26 queue.offer(curr.left); 27 } 28 if(curr.right != null) { 29 queue.offer(curr.right); 30 } 31 } 32 currLevel++; 33 } 34 return minLevel; 35 } 36 }