LeetCode——111. Minimum Depth of Binary Tree

问题描述:

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.

  这道题大致的意思是在一棵二叉树中求根节点到叶子结点的最小层数(最小距离)。

  上一题求的是求根节点到叶子结点的最大层数。
  我以为还是像上一道题一样从上往下走去更新层数,没想到出现了一个问题:如果一个节点有左子节点但没有右子节点,那么这个点肯定不算叶子结点,不满足题目要求。到这里我才发现原来我上一道题并没有判断当前点是否为叶子结点,就对层数进行了更新。不过因为上一道题是求最远的层数,所以无论如何,到最后结尾的永远是叶子结点。但是求最小层数就出现问题了。
  所以,标准答案的想法就是从下往上去更新层数,如果这个点只有左子节点或者右子节点,那么这个点的层数就是左子节点或右子节点的层数加1;如果这个点两个子节点都有,那么这个点的层数应该是左子节点和右子节点间取最小的。

public int minDepth(TreeNode root) {
        if(root == null) 
            return 0;

        int left = minDepth(root.left);
        int right = minDepth(root.right);
        return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;
    }

  后来想了想,又把原来的改了一下,其实从上到下也是可以的,只不过要在当前节点是叶子结点,即(root.left == null && root.right == null)时,才对最小层数进行更新,其他情况是继续往下遍历。

private int minLevel = 99999999;

    public int minDepth(TreeNode root) {
        if(root == null) 
            return 0;

        //上面是答案的方法,我自己想了想,在自己原方法上改进一下,形成了新的
        //其实就是在更新最小层数时,要当前节点是叶子结点的情况下,才能进行更新
        searchDepth(1, root);
        return minLevel;
    }

    public void searchDepth(int level, TreeNode root) {
        if(root.left == null && root.right == null) {
            if(level < minLevel) {
                minLevel = level;
            }
            return;
        }
        if(root.left != null)
            searchDepth(level+1, root.left);
        if(root.right != null)
            searchDepth(level+1, root.right);
    }

  这道题还是比较简单的,所以今天的解释也是比较简单。
  依旧,谢谢大家观看我的博客,如果有不明白的地方或者文中有错误的地方,欢迎大家指出,谢谢!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值