minimum-depth-of-binary-tree
/*
* 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.
* */
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public int run(TreeNode root) {
if(root == null)
return 0;
int i = run(root.left);
int j = run(root.right);
//左右子树有一个为空就是另外一边的深度加 1 为该节点的最小深度
return (i == 0 || j == 0) ? i + j + 1 : Math.min(i, j) + 1;
}
@Test
public void test() {
TreeNode root = new TreeNode(1);
TreeNode temp = root;
temp.left = new TreeNode(2);
temp.right = new TreeNode(3);
TreeNode temp1 = temp.left;
temp1.left = new TreeNode(4);
temp1.right = new TreeNode(5);
TreeNode temp2 = temp.right;
temp2.left = new TreeNode(6);
//temp2.right = new TreeNode(7);
System.out.println(run(root));
}