二叉树的最小深度

这是一篇关于计算二叉树最小深度的文章。主要内容包括理解二叉树的最小深度定义,即从根节点到最近叶子节点的距离。通过提供一个样例二叉树,文章解释了如何递归地寻找最小深度。在递归过程中,特别强调了当节点的一个子树为空时,仍需要继续搜索另一子树的情况。示例中给出了一个解决方案,包含一个名为`Solution`的类,其中`minDepth`方法利用递归计算最小深度。

给定一个二叉树,找出其最小深度。

二叉树的最小深度为根节点到最近叶子节点的距离。

样例

给出一棵如下的二叉树:

        1

     /     \ 

   2       3

          /    \

        4      5  

这个二叉树的最小深度为 2

【主要在递归时要注意,当有的节点有一个子树为空时,不是叶子节点要继续寻找】

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int minDepth(TreeNode root) {
        // write your code here
        if(root==null)
          return 0;
        if(root.left==null && root.right==null)
          return 1;
        int dep1=minDepth(root.left)+1;
        int dep2=minDepth(root.right)+1;
        
        if(dep1==1)//左空右不空
          dep1=Integer.MAX_VALUE;
        if(dep2==1)
          dep2=Integer.MAX_VALUE;
          
        if(dep1>dep2)
          return dep2;
        return dep1;
    }
}


//网上学习的方法

  1. public class Solution {  
  2.     public int minDepth(TreeNode root) {  
  3.         if(root == nullreturn 0;  
  4.         if(root.left == null)return minDepth(root.right) + 1;  
  5.         if(root.right == nullreturn minDepth(root.left) + 1;  
  6.           
  7.         return Math.min(minDepth(root.left), minDepth(root.right)) + 1;  
  8.     }  
  9. }  

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值