• [LeetCode] 111. Minimum Depth of Binary Tree ☆(二叉树的最小深度)


    [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度 (最小有3种解法)

    描述

    解析

    递归深度优先搜索

    当求最大深度时,我们只要在左右子树中取较大的就行了。

    然而最小深度时,如果左右子树中有一个为空会返回0,这时我们是不能算做有效深度的。

    所以分成了三种情况,左子树为空,右子树为空,左右子树都不为空。当然,如果左右子树都为空的话,就会返回1。

    广度优先搜索(类似层序遍历的思想)

    递归解法本质是深度优先搜索,但因为我们是求最小深度,并不一定要遍历完全部节点。如果我们用广度优先搜索,是可以在遇到第一个叶子节点时就终止并返回当前深度的。

    代码

    递归深度优先搜索

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int minDepth(TreeNode root) {
            if(root == null){
                return 0;
            }
            int depth = 0;
            if(root.left != null && root.right != null){
                int left = minDepth(root.left);
                int right = minDepth(root.right);
                depth = Math.min(left, right);
            } else if (root.left != null){
                depth = minDepth(root.left);
            } else if (root.right != null){
                depth = minDepth(root.right);
            }
            return depth + 1;
        }
    }

    广度优先搜索(类似层序遍历的思想)

    public class Solution {
        public int minDepth(TreeNode root) {
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            if(root!=null) queue.offer(root);
            int depth = 0;
            while(!queue.isEmpty()){
                int size = queue.size();
                depth++;
                for(int i = 0; i < size; i++){
                    TreeNode curr = queue.poll();
                    if(curr.left == null && curr.right == null){
                        return depth;
                    }
                    if(curr.left != null) queue.offer(curr.left);
                    if(curr.right != null) queue.offer(curr.right);
                }
            }
            return depth;
        }
    }
  • 相关阅读:
    POM (Project Object Model)简介
    Maven 依赖管理
    Maven仓库—Nexus环境搭建及简单介绍
    Maven的几个核心概念
    maven本地仓库的配置以及如何修改默认.m2仓库位置
    Maven修改镜像仓库地址
    Maven生命周期
    Maven 和 Ant 的区别?
    Maven简介
    Maven常用命令
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10614987.html
Copyright © 2020-2023  润新知