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;
        }
  • 相关阅读:
    PHP 5.5.0 Alpha5 发布
    Ubuntu Touch 只是另一个 Android 皮肤?
    MariaDB 10 已经为动态列提供文档说明
    Percona Toolkit 2.1.9 发布,MySQL 管理工具
    Oracle Linux 6.4 发布
    Ruby 2.0.0 首个稳定版本(p0)发布
    Apache Pig 0.11.0 发布,大规模数据分析
    Node.js 0.8.21 稳定版发布
    红薯 MySQL 5.5 和 5.6 默认参数值的差异
    Django 1.5 正式版发布,支持 Python 3
  • 原文地址:https://www.cnblogs.com/neuzk/p/9486095.html
Copyright © 2011-2022 走看看