package leetcode;
/*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 Minimum_depth_of_binary_tree {
public static void main(String[] args) {
}
public int run(TreeNode root) {//为什么简单地程序需要再增加一个方法呢?因为本算法,当根节点为空返回0,当是叶子节点为空的时候则需要一个最大值,去实现算法
//为了实现这两种情况,所以先在第一个函数中设置root为空的情况,当不为空的时候则进入另一个函数
if(root == null)
return 0;
return getMin(root);
}
private int getMin(TreeNode root) {
// TODO Auto-generated method stub
if(root == null) //当节点为空,赋值为最大值,这样当左右节点两边一边为空,一边不为空,则以不为空为依据.因为高度必须是根节点到叶子节点的距离
return Integer.MAX_VALUE;
if(root.left == null && root.right == null) {//当左右两节点为空时,则高度返回为1
return 1;
}
int left = getMin(root.left); //求出左子树高度
int right = getMin(root.right); //求出右子树高度
return Math.min(left, right)+1; //左右两边高度的最小值+1,+1是因为算上根节点...
}
}