求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
分4种情况分析:
1 没有根节点
2 只有根节点
3 二叉树的根节点只有左子树 or 只有右子树
4 根节点左子树和右子树都有
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型
*/
public int run (TreeNode root) {
// 没有根节点
if (root == null) return 0;
// 只有根节点
if (root.left == null && root.right == null ) return 1;
// 二叉树的根节点只有左子树 or 只有右子树
if (root.left == null || root.right == null) return Math.max(run(root.left),run(root.right)) + 1;
// 根节点左子树和右子树都有
return Math.min(run(root.left),run(root.right)) + 1;
}
}