[Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度

news/2024/6/19 1:40:51

Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

递归法

复杂度

时间 O(N) 空间 O(H) 递归栈空间

思路

简单的递归。递归条件是,它的最大深度是它左子树的最大深度和右子树最大深度中较大的那个加1。基础条件是,当遇到空节点时,返回深度为0。该递归的实质是深度优先搜索。

代码

public class Solution {

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

}

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.

递归法

复杂度

时间 O(N) 空间 O(H) 递归栈空间

思路

当求最大深度时,我们只要在左右子树中取较大的就行了,然而最小深度时,如果左右子树中有一个为空会返回0,这时我们是不能算做有效深度的。所以分成了三种情况,左子树为空,右子树为空,左右子树都不为空。当然,如果左右子树都为空的话,就会返回1。

代码

public 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;
    }
}

广度优先搜索

复杂度

时间 O(N) 空间 O(B)

思路

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

代码

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;
    }
}

迭代加深有限深度优先搜索

复杂度

时间 O(N) 空间 O(D)

思路

英文名是Iterative Deepening Depth Limited Search.然而,广度优先搜索有一个致命缺陷就是,一旦分支变多,消耗空间就太大。这里我们还有改进的余地,就是用迭代加深的有限深度优先搜索。该算法每次迭代是一次有限深度优先搜索,如果本轮迭代没有发现目标(这题的目标是第一个叶子结点),则增加深度上限重新进行有限深度优先搜索。读者可能觉得这样会带来很多重复计算,但实际上经过数学证明后可以发现,该算法的时间复杂度和广度优先搜索是在一个数量级的,并没有太大的增加,而他的空间消耗仅仅是限制的深度。详情请翻阅Artificial Intelligence : A Modern Approach。

代码

public class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        return iterativeDeepeningDFS(root);
    }
    private boolean depthLimitedSearch(TreeNode root,int depth){
        boolean left = false;
        boolean right = false;
        if(depth>0){
            if(root.left==null&&root.right==null){
                return true;
            }
            if(root.left!=null) {
                left = depthLimitedSearch(root.left, depth-1);
            }
            if(root.right!=null) {
                right = depthLimitedSearch(root.right, depth-1);
            }
            return left||right;
        } else {
            return false;
        }
    }
    private int iterativeDeepeningDFS(TreeNode root){
        int thisDepth = 1;
        boolean foundMin = false;
        while(true){
            foundMin = depthLimitedSearch(root,thisDepth);
            if(foundMin){
                return thisDepth;
            } else {
                thisDepth++;
            }
        }
    }
}

http://www.niftyadmin.cn/n/2901005.html

相关文章

prototype 与 __proto__

原文&#xff1a;http://rockyuse.iteye.com/blog/1426510 说到prototype&#xff0c;就不得不先说下new的过程。 我们先看看这样一段代码&#xff1a; 1 <script type"text/javascript">2 var Person function () { };3 var p new Person();4 </script&g…

[面经] 南京SAP面试(上)

背景 博主乃985弱校的小硕一枚&#xff0c;在南京某外企工作了两年&#xff0c;如今的公司还不错&#xff0c;待遇还行&#xff0c;做的东西也比較有意思。在南京这个地方&#xff0c;给力的公司不太多&#xff0c;仅仅要是跟亲戚朋友聊到我在南京做IT&#xff0c;无一例外都会…

操作MySQL出错提示“BLOB/TEXT column used in key specification without a key length”解决办法

mysql出错提示“BLOB/TEXT column used in key specification without a key length”解决办法 一、问题 pandas对象将DataFrame数据保存到mysql中时&#xff0c;出现错误提示&#xff1a;   BLOB/TEXT column used in key specification without a key length 或者 在MyS…

Linux platform平台总线、平台设备、平台驱动

平台总线&#xff08;platform_bus&#xff09;的需求来源&#xff1f; 随着soc的升级&#xff0c;S3C2440->S3C6410->S5PV210->4412&#xff0c;以前的程序就得重新写一遍&#xff0c;做着大量的重复工作&#xff0c; 人们为了提高效率&#xff0c;发现控制器的操作逻…

【js】如何用 js 把数据从一个页面传到另一个页面(sessionStorage.本地存储)

1、利用本地存储 通过相同的 key 完成本地数据的存入和读取&#xff0c;value 是要存和取的数据。 &#xff08;key是随意起的&#xff0c;只要 存和取时 相同就行&#xff1b;&#xff09; sessionStorage.setItem(“key”, “value”); // 存 sessionStorage.getItem(“key”…

linux下安装.run文件

2019独角兽企业重金招聘Python工程师标准>>> 比如realplay.run 安装方法如下 chmod x realplay.run ./realplay.run 然后他就会执行安装了&#xff0c;在过程中可能会要求你输入yes或no 安装完后就可以用了 ,chmod实际上是加权限命令 。&#xff0b;x表示可以执行ch…

读取Excel复杂的数据

涉及到合并单元格的数据读取&#xff1a; package com.util;import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress;import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStre…

【cmd】 如何通过cmd打开 jupyter,在jupyter中如何打开文件夹

前提是已经安装好了 1、通过 cmd 打开jupyter 在cmd中输入 jupyter notebook&#xff0c;等待片刻就会自动打开页面&#xff0c;也可以自己打开&#xff1a; http://localhost:8888 2、在jupyter中打开文件夹 在cmd 输入 jupyter notebook 之前 先输入文件夹所在的路径&#…