求二叉树的最小深度

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是因为算上根节点...
        }
          
}
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值