111. 二叉树的最小深度

广度优先搜索

class Solution {
    public int minDepth(TreeNode root) {

        if (root == null){
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        int depth = 1;

        queue.add(root);

        while (!queue.isEmpty()){

            int size = queue.size();

            for (int i = 0; i < size; i++) {

                TreeNode temp = queue.poll();

                /**
                 * 如果左右孩子都为空,就返回当前的深度
                 */
                if (temp.left == null && temp.right == null){
                    return depth;
                }
                
                if (temp.left != null){
                    queue.add(temp.left);
                }

                if (temp.right != null){
                    queue.add(temp.right);
                }
            }

            depth++;
        }

        return depth;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

深度优先搜索

class Solution {

    public int minDepth(TreeNode root) {

        if (root == null){
            return 0;
        }

        /**
         * 递归
         * 假设已经求出了根节点左右子树的最小深度,那总的最小深度就等于其加1
         * 递归需要栈空间,而栈空间取决于递归的深度
         */
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);

        /**
         * 如果根节点只有一个孩子,即最小值等于0,那么不能认为其最短深度为0,而应该是那个孩子的深度再加1
         */
        if (Math.min(leftDepth, rightDepth) == 0){
            return Math.max(leftDepth, rightDepth) + 1;
        }

        return Math.min(leftDepth, rightDepth) + 1;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

posted @ 2021-10-27 18:57  振袖秋枫问红叶  阅读(43)  评论(0)    收藏  举报