/**
 *	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.
 *
 *	Author: matao
 *
 */


class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x) { val = x; }
}

public class MinimumDepthOfBinaryTree {
	public static int minDepth(TreeNode root) {
		if (root == null){
            return 0;
        }
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        if (leftDepth == 0) {
            return rightDepth + 1;
        }
        if(rightDepth == 0) {
            return leftDepth + 1;
        }
        return leftDepth + 1 < rightDepth + 1 ? leftDepth + 1: rightDepth + 1;
    }

    public static void main(String[] args) {
        TreeNode testTree1 = new TreeNode(1);
        System.out.println(minDepth(testTree1));
        TreeNode testTree2 = null;
        System.out.println(minDepth(testTree2));
        TreeNode testTree3 = new TreeNode(1);
        testTree3.left = new TreeNode(2);
        System.out.println(minDepth(testTree3));
    }
}
@@ -517,16 +517,55 @@
 .right);
+%0A%0A        // %E6%9F%90%E7%BB%93%E7%82%B9%E5%8F%AA%E6%9C%89%E5%8D%95%E5%88%86%E6%94%AF%EF%BC%8C%E8%8B%A5%E4%B8%8D%E5%88%A4%E6%96%AD%EF%BC%8C%E7%9B%B4%E6%8E%A5%E6%AF%94%E8%BE%83%E7%9A%84%E5%8C%96%E3%80%82%E4%BC%9A%E8%BF%94%E5%9B%9E0;
 %0A       

add comment