LeetCode每日一题(20200821)

原题地址

终于是一道简单的题目了,是为了让大家周末愉快吗^_^

思考过程:

第一反应是用递归处理,然后需要分情况。1.树是空,返回0;2.两个节点都为空,返回1;3.树左节点为空,返回1+右节点最小深度;4.右节点为空,返回1+左节点最小深度;5.两个节点都不为空,返回左节点最小深度和右节点最小深度的最小值再+1。

代码实现:

public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        if (root.left == null) {
            return 1 + minDepth(root.right);
        }
        if (root.right == null) {
            return 1 + minDepth(root.left);
        }
        return 1 + Math.min(minDepth(root.left), minDepth(root.right));
    }

执行结果:

算法复杂度分析:

时间复杂度:O(n),其中 n是树节点数。

空间复杂度:O(1)。

 

查看官方解法:

官方提供了两张解法,深度优先和广度优先,我个人思路是属于深度优先,代码实现上,官方深度度优先代码和我个人实现的差不多,就不再赘述,以下是官方广度优先代码:

    class QueueNode {
        TreeNode node;
        int depth;

        public QueueNode(TreeNode node, int depth) {
            this.node = node;
            this.depth = depth;
        }
    }

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

        Queue<QueueNode> queue = new LinkedList<QueueNode>();
        queue.offer(new QueueNode(root, 1));
        while (!queue.isEmpty()) {
            QueueNode nodeDepth = queue.poll();
            TreeNode node = nodeDepth.node;
            int depth = nodeDepth.depth;
            if (node.left == null && node.right == null) {
                return depth;
            }
            if (node.left != null) {
                queue.offer(new QueueNode(node.left, depth + 1));
            }
            if (node.right != null) {
                queue.offer(new QueueNode(node.right, depth + 1));
            }
        }

        return 0;
    }

执行结果:

 

总结:

这题是树相关的问题中,比较简单的类型,但是就是这么简单的题目,我在解题过程中,也没有一下子就把所有情况分清楚,导致前面几次提交都是错误的,如下。。。对待有把握的简单题目,还是不能大意,要多加思考。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值