Minimum Depth of Binary Tree 二叉树的最小深度

2023-05-16

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.

出处:http://www.programcreek.com/2013/02/leetcode-minimum-depth-of-binary-tree-java/

下边的这个解法简直是机智:维护两个List,其中count的那个List尤为重要,都跟节点同步,add或者poll元素,记录当前元素是第几层,简直是不能更机智。如果不懂了,画一个图走一下流程,就体会出来了

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        if(root==null)  return 0;
        LinkedList<TreeNode> list=new LinkedList<TreeNode>();
        LinkedList<Integer> count = new LinkedList<Integer>();
        list.add(root);
        count.add(1);
        while(!list.isEmpty()){
            TreeNode temp=list.poll();
            int cal=count.poll();
            if(temp.left==null && temp.right==null) return cal;
            if(temp.left!=null){
                list.add(temp.left);
                count.add(cal+1);    //这个和下边的实现了第n层有几个节点,就让这个n存储几个
            }      
            if(temp.right!=null){
                list.add(temp.right);
                count.add(cal+1);    //这个和上边的实现了第n层有几个节点,就让这个n存储几个
            }     
        }
        return count.poll();    //必须有返回语句,不然报错
    }
}

下边的转自:http://blog.csdn.net/sbitswc/article/details/26526031

下边我故意交叉用了ArrayList和 LinkedList,而在对outter用Inner进行赋值的时候竟然没有出错,可见ArrayList和 LinkedList的关系

public class Solution {
    public int minDepth(TreeNode root) {
        ArrayList<TreeNode>outter=new ArrayList<TreeNode>();
        if(root==null) return 0;
        outter.add(root);
        int count=1;
        while(!outter.isEmpty()){
            LinkedList<TreeNode>inner=new LinkedList<TreeNode>();
            for(TreeNode temp:outter){
                if(temp.left==null && temp.right==null) return count;
                if(temp.left!=null) inner.add(temp.left);
                if(temp.right!=null)    inner.add(temp.right);
            }
            ++count;  //在整个遍历完outter中的元素之后再行加一
            outter=new ArrayList<TreeNode>(inner); //把inner赋给了outter,即保证每一层都在同一次迭代里边
        }
        return count;
    }
}


下边的参考这篇博客:http://www.blogjava.net/menglee/archive/2013/12/21/407856.html

递归写法

public class Solution {
    public int minDepth(TreeNode root) {
        if(root==null)  return 0;
        else if(root.left==null && root.right==null)    return 1;
        else{   //有了上边的else语句,这儿必然满足root.left和root.right里边至少有一个肯定不为空

//下边之所以有Integer.MAX_VALUE,是因为left和right至少有一个为空,那么深度肯定以不为空的那个计,所以把这个置为最大,以防干扰

            int left=root.left==null? Integer.MAX_VALUE:minDepth(root.left);
            int right=root.right==null? Integer.MAX_VALUE:minDepth(root.right);
            return Math.min(left,right)+1; 
        }
    }
}


跟上一种写法思想一样,只不过在处理left和right有且仅有一个为空的时候写法稍微有点不同,没有用Integer.MAX_VALUE

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


下边的写法就是上边两种写法,只不过看看更简单了,之所以上边写的没有这么简单,真的是因为对于递归理解的不够好

出处:http://blog.csdn.net/xudli/article/details/8492064

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


下边的程序对二叉树进行BFS,由于是按层遍历的,因此如果在某一层发现了一个叶子节点,那么就找到了最小深度,此时返回当前深度即可

public class Solution {
    public int minDepth(TreeNode root) {
        if(root==null)  return 0;
        int depth=1;
        int curlevel=1;  //物理意义是当前层
        int nextlevel=0;  //物理意义是下一层
        Queue<TreeNode> queue=new LinkedList<TreeNode>(); //切记切记,queue是由LinkedList实现的
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode node=queue.poll();
            --curlevel; //每poll一个元素,当前层计数curlevel减1
            if(node.left==null && node.right==null) return depth;
            if(node.left!=null){
                queue.add(node.left);
                ++nextlevel;  //基于当前层,如果有add,那么下一层计数即nextlevel加1
            }
            if(node.right!=null){
                queue.add(node.right);
                ++nextlevel;   //基于当前层,如果有add,那么下一层计数即nextlevel加1
            }
            if(curlevel==0){   //如果当前层为0,即所有元素从左到右遍历完
                if(nextlevel!=0)   
                    ++depth;    //如果下一层还有节点,那么depth加1
                curlevel=nextlevel;  //把下一层个数赋值给当前层
                nextlevel=0;  //下层置0
            }
        }
        return depth;
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Minimum Depth of Binary Tree 二叉树的最小深度 的相关文章

  • 基本树概念:定义祖先

    祖先的定义是什么 更具体地说 E 会是 H 的祖先吗 或者更简单地说 F C A 是 H 的祖先 也许甚至是G 我只是想澄清这个简单的概念 E 不是 H 的祖先 它是uncle因为它是一个siblingF 的parent of H F C
  • 使用node.js fs.writeFile写入二进制数据以创建图像文件

    我正在尝试用 node js 编写画布数据fs writeFile https nodejs org api fs html fs fs writefile file data options callback作为二进制文件 JPEG 文件
  • 为什么 C 没有二进制文字?

    我经常希望我能在 c 中做这样的事情 val1 0b00001111 clear high nibble val2 0b01000000 set bit 7 val3 0b00010000 clear bit 5 使用这种语法似乎是对 C
  • RAM 存储二进制数和汇编语言的冒泡排序

    我必须使用 ARM v7 执行一个例程 在 RAM 内存中存储 10 个二进制数 然后使用冒泡排序对这些数字从高到低进行排序 我应该如何开始 func bubbleSortAscendingU32 ldr r3 r0 4 mov r1 9
  • 如何递归探索Python嵌套字典? [复制]

    这个问题在这里已经有答案了 我很好奇是否有一种方法可以在 python 中递归地探索嵌套字典 我的意思是 假设我们有一个如下示例 d a b c 1 2 3 获取最里面字典的内容需要什么代码 c 1 2 3 遍历a and b 在这种情况下
  • 绘制java类的依赖关系图

    嘿嘿 我正在寻找像 JDepend 这样的工具来为 java 类文件绘制图表 JDepend 看起来很好 但它没有从 deps 中解析 deps 也许我只是缺少一些特殊选项 直接输出为 dot 格式或图像会很好 谢谢 你可以试试Java依赖
  • 使用递归求数组的最小值?

    好吧 所以我一直在尝试用 Java 来理解递归 我可以完成简单的任务 例如求和 反转等 但我一直在努力做这个练习 我试图使用递归找到数组中的最小数字 但始终得到 0 0 的答案 我对递归的理解是 我需要增加一个元素 然后提供一个结束递归的基
  • 将数据库结果转为数组

    我刚刚为组织查询分层数据的 闭包表 方式制作了更新 添加 删除部分 如本幻灯片第 70 页所示 http www slideshare net billkarwin sql antipatterns strike back http www
  • 将 python NLTK 解析树保存到图像文件[重复]

    这个问题在这里已经有答案了 这可能会复制这个 stackoverflowquestion https stackoverflow com questions 23429117 saving nltk drawn parse tree to
  • 如何按层次结构对文件路径名进行排序?

    我想按层次结构对文件名进行排序 假设我有以下文件夹列表 D Movies Hollywood Comedy adultcomedy D Movies Hollywood Comedy horrorcomedy D Movies Hollyw
  • 为什么 -INT_MIN = INT_MIN 在有符号的二进制补码表示中?

    我仍然没有找到为什么最低的有符号负数没有等效的有符号正数的原因 为简单起见 我的意思是 3 位二进制数 100 是 4 但我们不能有符号格式的正 4 因为我们不能 它溢出了 那么我们如何知道补码 1000 是 4 1000 0000 是 1
  • 如何使用 d3.v4 中的 JSON 数据创建树布局 - 不使用 stratify()

    我正在尝试将一些 d3 代码从 v3 更新到版本 4 我有一个使用 JSON 数据的树形图 d3 v4 示例展示了如何使用 stratify 将表格数据 例如flare csv 转换为分层数据https bl ocks org mbosto
  • 如何从 wfstream 读取二进制数据?

    我从文件读取数据时遇到一个小问题 我希望能够读取 wstring 以及任意大小的原始数据块 大小以字节为单位 std wfstream stream file c str std wstring comType stream gt gt c
  • Webix 树节点的 Font Awesome 图标

    Webix 与 Font Awesome 集成 http docs webix com desktop icon types html 但是如何使用 Font Awesome 图标代替树中的默认文件夹 文件图标来设置各个节点的样式呢 这是我
  • 在哈希图中存储字符和二进制数

    我正在尝试存储字母到二进制数的映射 这是我的映射 h 001 i 010 k 011 l 100 r 101 s 110 t 111 为此 我创建了一个哈希映射并存储了键值对 我现在想显示给定句子的相应二进制值 这是我的代码 package
  • 非二叉树的中序树遍历

    对于比二叉树更宽的树 术语 中序遍历 是否有明确定义的含义 或者 前 和 后 顺序是唯一有意义的 DFS 类型吗 我的意思是与n每个节点 gt 2 个子节点 我猜是为了n这甚至可能意味着之后要转到 根 n 2孩子们 但这曾经这样使用过吗 那
  • 互联网 RFC 数据包图中预期的位(不是字节)顺序是哪个

    我正在我的家庭有线网络上解析 ICMPv6 数据报 但在特定 RFC 中找不到对位排序约定的明确提及 多字节字段是网络顺序的 但是字节内的位又如何呢 机器是按字节寻址的 但网络硬件对位进行序列化 在图表中 8 位字段 左侧 的一位最终位于无
  • 使用 IE11 的工作程序使用 multipart/form-data 发送二进制数据

    我正在尝试发送multipart form data来自 IE 的工作人员 我已经使用 Chrome Firefox Safari 完成了此操作formData对象 不支持IE 我需要一个手动的 我发送的二进制数据是 crypto js 加
  • 如何在 R 中将字符串解析为层次结构或树

    有没有办法将表示组的字符串解析为 R 中的层次结构 假设我的小组结构如下 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 3 1 1 3 1 1 1 3 2 1 1 3 3 1 2 1 2 1 1 2 1 1 1 2 1 2 1
  • 在 C++ 中分割大文件

    我正在尝试编写一个程序 该程序接受一个大文件 任何类型 并将其分成许多较小的 块 我想我已经有了基本的想法 但由于某种原因我无法创建超过 12 kb 的块大小 我知道谷歌等上有一些解决方案 但我更感兴趣的是了解这个限制的根源是什么 然后实际

随机推荐