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;
        }
  • 相关阅读:
    [转]ThinkCMF框架任意内容包含漏洞分析复现
    nodejs环境安装
    ffmpeg+nginx-rtmp-module
    activemq安装
    mysql审计插件
    sql优化工具SQLAdvisor的安装
    Harbor安装(docker-compose) -- 企业级Registry仓库
    在CentOS上部署kubernetes1.9.0集群
    3-基础概念(数据模型、时序 4 种类型、作业和实例)
    1-什么是 Prometheus
  • 原文地址:https://www.cnblogs.com/neuzk/p/9486095.html
Copyright © 2011-2022 走看看