zoukankan      html  css  js  c++  java
  • 打印二叉树

     1 import math
     2 
     3 #  树的分析
     4 origin = [30, 20, 80, 40, 50, 10, 60, 70, 90]
     5 length = len(origin)  # 节点 9
     6 h = math.ceil(math.log(length, 2))  # >3  所以深度为4
     7 max_length = 2 ** (h - 1)  # 满二叉树的叶子数
     8 index = 2 ** h - 1  # 总节点数 15
     9 o = origin + [0] * (index - length)
    10 new_list = len(o) * [0]
    11 
    12 # 计算空格
    13 for i in range(1, h + 1):
    14     times = 2 ** (i - 1)  # 每一层的个数
    15     index //= 2
    16     count = 1
    17     new_list = len(o) * [0]  # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    18     for j in range(times - 1, times * 2 - 1):
    19         if count > times*10:break
    20         if count % 2 != 0:
    21             new_list[index*count+(count-1)] = o[j]
    22             count += 1
    23         else:
    24             count += 1
    25             new_list[index*count+(count-1)] = o[j]
    26             count += 1
    27     # print(new_list)
    28     for i in new_list:
    29         print('  ', end='') if i == 0 else print(i,end='')
    30     print()
    31 
    32 # 打印中间数
    33 origin = [30, 20, 80, 40, 50, 10, 60, 70, 90]
    34 length = len(origin)  # 节点 9
    35 h = math.ceil(math.log(length, 2))  # >3  所以深度为4
    36 index = 2 ** h - 1  # 满树的总节点数 15
    37 
    38 for i in range(1,h+1):
    39     times = 2 ** (i - 1)
    40     for j in range(times - 1, times * 2 - 1):
    41         if j >= length: break
    42         # print(index)
    43         print('{:^{}}'.format(origin[j], index*2),end='**'*1)
    44     print()
    45     index //=  2

     

    为什么要坚持,想一想当初!
  • 相关阅读:
    堆和栈的区别
    MyKTV点歌系统
    KTV音乐播放的实现
    继承与多态之汽车租赁系统
    使用集合组织相关数据
    用户登陆及异常的处理
    oracle函数详解
    Java中的多线程
    JAVA Map集合框架的使用
    Java中迭代器初深
  • 原文地址:https://www.cnblogs.com/JerryZao/p/9607853.html
Copyright © 2011-2022 走看看