Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Idea: Recursive Implementation, with a smaller depth of + 1 in the left and right nodes.
NOTE: If either of the left and right subtree is null, the depth of the subtree that is not null should prevail, rather than the depth 0 of null.
public class Solution { public int minDepth(TreeNode root) { if (root == null) return 0; if (root.left == null) return minDepth(root.right) + 1; if (root.right == null) return minDepth(root.left) + 1; else { int minLeft = minDepth(root.left); int minRight = minDepth(root.right); return (minLeft < minRight ? minLeft : minRight) + 1; } } public static void main(String[] args) { TreeNode root = new TreeNode(10); root.left = new TreeNode(5); root.right = new TreeNode(5); root.right.left = new TreeNode(9); System.out.println(new Solution().minDepth(root)); }}
View code