zoukankan      html  css  js  c++  java
  • 二叉树的宽度和深度

    一、深度

    递归版本

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

    非递归版本

    思想:二叉树的深度就是指二叉树有几层,那么我们可以使用层序遍历来实现。

    public static int getDeep(TreeNode root) {
            if(root == null) return 0;
            LinkedList<TreeNode> list = new LinkedList<>();
            list.add(root);
            int count = 1; //每层的结点数
            int level = 1; //层数
            while(!list.isEmpty()) {
                int size = 0; //临时保存下层的结点数
                for(int i = 0; i < count; i++) {
                    TreeNode p = list.removeFirst();
                    if(p.left != null) {
                        size++;
                        list.addLast(p.left);
                    }
                    if(p.right != null) {
                        size++;
                        list.addLast(p.right);
                    }
                }
                //如果下一层没有结点,则结束循环
                if(size == 0) break;
                count = size;
                level++;
            }
            return level;
        }

    二、宽度

    思想:二叉树的宽度就是最宽的那一层的节点数,所以还是需要层序遍历的思想,先计算每层的结点数,然后找出最大的。

    public static int getWidth(TreeNode root) {
            if(root == null) return 0;
            LinkedList<TreeNode> list = new LinkedList<>();
            list.add(root);
            int count = 1; //每层的结点数
            int width = 1; //宽度
            while(!list.isEmpty()) {
                int size = 0; //临时保存下层的结点数
                for(int i = 0; i < count; i++) {
                    TreeNode p = list.removeFirst();
                    if(p.left != null) {
                        size++;
                        list.addLast(p.left);
                    }
                    if(p.right != null) {
                        size++;
                        list.addLast(p.right);
                    }
                }
                if(size == 0) break; //如果下一层没有结点,则结束循环
                if(size > width) width = size;
                count = size;
            }
            return width;
        }
  • 相关阅读:
    BootStrap详解之(一)
    Centos6.5安装与配置Tomcat-8的方法
    Centos下安装jdk详解
    Html基础详解之(jquery)之二
    四层和七层负载均衡的区别
    linux下用script和scriptreplay对命令行操作录像
    Linux批量部署工具Expect
    Linux日常之Ubuntu系统中sendmail的安装、配置、发送邮件
    Linux日常之定时向文件传内容
    Linux日常之以当前时间命名文件
  • 原文地址:https://www.cnblogs.com/neuzk/p/9486095.html
Copyright © 2011-2022 走看看