zoukankan      html  css  js  c++  java
  • [Algorithm] Find Max Items and Max Height of a Completely Balanced Binary Tree

    A balanced binary tree is something that is used very commonly in analysis of computer science algorithms. In this lesson we cover how to determine the maximum number of items it can accommodate.

    We follow this with a discussion on the maximum height of a binary tree given we need to accommodate n items.

                    O
               ╱       ╲
             ↙            ↘
           O                O
         ↙   ↘           ↙    ↘
       O       O        O       O
     ↙  ↘    ↙  ↘    ↙  ↘    ↙  ↘
    O    O   O   O   O    O   O   O
    
    level 0 : 1 (2 ^ 0)
    level 1 : 2 (2 ^ 1)
    level 2 : 4 (2 ^ 2)
    ...
    
    2^0 + 2^1 + 2^2 + 2^3 .... + 2^n
    =>
    Height of tree  |  Level  |  Items in level      |    Total
         1               0             1  (+1 lie)          2
         2               1             2                    4
         3               2             4                    8
         4               3             8                   16
    
    2^level + 2^level - 1
    2*(2^level) - 1
    2^(level + 1)  - 1
    2^h - 1
    /**
     * Returns the max items that can exist in a perfectly balanced binary tree
     */
    export function maxItems(height: number) {
      return 2 ** height - 1;
    }
    /**
     * Returns the max height of a balanced binary tree given n items
     */
    export function maxHeight(items: number) {
      return Math.log2(items + 1);
    }
  • 相关阅读:
    校门外的树
    学生档案
    冒泡排序法
    寻找最大数序列
    初识结构体
    找零钱
    冒泡的应用
    关于数组的逆序重放
    关于质数
    字符串转换为日期格式
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10338493.html
Copyright © 2011-2022 走看看