leetcode(31).111. Minimum Depth of Binary Tree

题意:给定一个二叉树,查找其最小深度。

初步分析:递归的获取到最小深度。(从上往下,左右子树深度相比,每次递归都取最小的那个再加1)

public class Solution {
    public int minDepth(TreeNode root) {
        if(root == null)
            return 0;
 
        return Math.min(minDepth(root.left),minDepth(root.right))+1;
    }
}
但是,这样有错

左右子树有一个为空的时候,那么min就直接就是0了(不管另一个子树有多高)

也就是说不管是

*  还是  *

          *

高度都是1,显然是不对的。

比如:

  a

b

返回1.但应该是2,因为结点b的高度为1(min(0,0)+1),但是a的高度为(min(b,0)+1)即(min(1,0)+1)即1.

我们发现,左结点或者右结点有一者不为空的时候,取小的时候会直接抹掉另一个子树的高度。

所以这种情况应该直接取不为空那一边子树的高度(再加1)

深度优先搜索:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if(root == null)
            return 0;
        int dep = 0;
        if(root.left!=null && root.right!=null)
            dep = Math.min(minDepth(root.left),minDepth(root.right));
        if(root.left == null)    //左子树为空,右子树不为空,取右子树的高度
            dep = minDepth(root.right);
        if(root.right == null)    //右子树为空。左子树不为空,取左子树的高度
            dep = minDepth(root.left); 
        return dep+1;
    }
}


广度优先搜索(将每一层不是叶子结点的放入层次遍历队列中,每次取出一层,每遍历一层高度加一,直到遇到叶子节点为止):

public int minDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(root);
    int depth = 1;  //按层记高度,根节点是第一层,高度为一
    while (!queue.isEmpty()) {
        int l = queue.size();     
        for (int i = 0; i < l; i++) {     
            TreeNode n = queue.poll();     //取出当前层所有结点
            if (n.left == null && n.right == null) {  //到叶子节点就返回高度
                return depth;
            } 
            if (n.left != null) {           //将不为空的结点放入下一层(只要不是叶子节点(左右都为空)就要继续计数)
                queue.add(n.left);
            }
            if (n.right != null) {
                queue.add(n.right);
            }
        }
        depth++;  //每一层,高度加一
    }
    return depth;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值