Minimum Depth of a Binary Tree (easy)
Problem Statement
Find the minimum depth of a binary tree. The minimum depth is the number of nodes along the shortest path from the root node to the nearest leaf node.
Example 1:
Example 2:
Try it yourself
Try solving this question here:
import java.util.*;class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}};class MinimumBinaryTreeDepth {public static int findDepth(TreeNode root) {// TODO: Write your code herereturn -1;}public static void main(String[] args) {TreeNode root = new TreeNode(12);root.left = new TreeNode(7);root.right = new TreeNode(1);root.right.left = new TreeNode(10);root.right.right = new TreeNode(5);System.out.println("Tree Minimum Depth: " + MinimumBinaryTreeDepth.findDepth(root));root.left.left = new TreeNode(9);root.right.left.left = new TreeNode(11);System.out.println("Tree Minimum Depth: " + MinimumBinaryTreeDepth.findDepth(root));}}
Solution
This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only difference will be, instead of keeping track of all the nodes in a level, we will only track the depth of the tree. As soon as we find our first leaf node, that level will represent the minimum ...