# Python 实现列表与二叉树相互转换并打印二叉树封装类-详细注释+完美对齐
from binarytree import build
import random # https://www.cnblogs.com/liw66/p/12133451.html class MyBinaryTree:
lst = [] def __init__(self, lst=[]):
MyBinaryTree.lst = lst class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right def getTreeFromList(self, _list=None):
if _list is None: _list = MyBinaryTree.lst
if _list is None: return [] len_all = len(_list) # 整个列表的长度
lay = 0 # 层数
loc = 0 # 结果列表位置
lay_list = [] # 层列表
node_list = [] # 节点列表
while len_all > 0:
len_lay = pow(2, lay) # 层列表的长度,每层的长度为 2^lay,2^0、2^1、2^2、2^3、...
lay_list.append(_list[loc:(loc + len_lay)]) # 从 _list 切片得到该层的元素列表,添加到 lay_list 中
tail = len(lay_list) - 1 # lay_list 的尾节点索引
# 对 lay_list 的尾节点(每个节点元素都为列表)进行循环遍历,用列表中的每个元素构建TreeNode添加到node_list中
for j in range(len(lay_list[tail])):
# 转换层列表为:[[5], [2, 9], [10, 1, 10, 5], [0, 9, 1]]
node_list.append(MyBinaryTree.TreeNode(lay_list[tail][j])) # 将列表索引 j 元素构建TreeNode添加到node_list中 # 为上一层的父节点 TreeNode 元素添加 left、或right 值
# if lay_list[tail][j] and lay > 0: # 在 python 中0、空都为假,非零为真,所以这样将导致 lay_list[tail][j] 为 0 时没能填充
if lay_list[tail][j] is not None and lay > 0: # 必须改为这样,才能避免 lay_list[tail][j] 为 0 时没能填充
if j % 2 == 0:
node_list[pow(2, lay - 1) - 1 + j // 2].left = node_list[-1]
else:
node_list[pow(2, lay - 1) - 1 + j // 2].right = node_list[-1] loc += len_lay
len_all -= len_lay
lay += 1 return node_list, lay_list def getListFromTree(self, root=None):
node_list = []
if root is None:
node_list = self.getTreeFromList()[0] root = node_list[0] def treeRecursion(root, i, _list):
if root is None:
return len1 = len(_list)
if len1 <= i:
for j in range(i - len1 + 1):
_list.append(None) _list[i] = root.val
treeRecursion(root.left, 2 * i, _list)
treeRecursion(root.right, 2 * i + 1, _list) _list = []
treeRecursion(root, 1, _list)
while _list and _list[0] is None:
del (_list[0])
return _list def printTree(self, node_list=[]):
if node_list is None:
node_list, _ = self.getTreeFromList() def getNodeName(node, name="Node"):
return "None" if node is None or node.val is None else name + "{:0>2d}".format(node.val) print("node:".ljust(7), "val".ljust(5), "left".ljust(7), "right")
for node in range(len(node_list)):
print(getNodeName(node_list[node]).ljust(6), end=": ")
print((getNodeName(node_list[node], "") + ", ").ljust(6),
(getNodeName(node_list[node].left) + ", ").ljust(8),
getNodeName(node_list[node].right), sep='') def test_binarytree(list1):
mytree = MyBinaryTree(list1) list2 = mytree.getListFromTree()
print("转换后列表为:{}".format(list2))
print("原来的列表为:{}".format(list1))
print("转换层列表为:{}".format(mytree.getTreeFromList()[1]))
print("转换前后的的列表是否相等:{}".format(list1 == list2)) print()
print("原来的列表转换为二叉树:{}".format(build(list1)))
print("转换的列表转换为二叉树:{}".format(build(list2))) print("二叉树节点列表为(完美对齐):")
mytree.printTree(mytree.getTreeFromList()[0]) list1 = [0, 1, 2, 3, 4, 5, 6, None, 7, None, 9, None, None, 10, ]
# list1 = [i for i in range(100)]
# list1 = [random.randint(0, 99) for i in range(20)]
test_binarytree(list1) # S:\PythonProject\pyTest01\venv\Scripts\python.exe S:/PythonProject/pyTest01/main.py
# 转换后列表为:[0, 1, 2, 3, 4, 5, 6, None, 7, None, 9, None, None, 10]
# 原来的列表为:[0, 1, 2, 3, 4, 5, 6, None, 7, None, 9, None, None, 10]
# 转换层列表为:[[0], [1, 2], [3, 4, 5, 6], [None, 7, None, 9, None, None, 10]]
# 转换前后的的列表是否相等:True
#
# 原来的列表转换为二叉树:
# ____0__
# / \
# __1 2___
# / \ / \
# 3 4 5 _6
# \ \ /
# 7 9 10
#
# 转换的列表转换为二叉树:
# ____0__
# / \
# __1 2___
# / \ / \
# 3 4 5 _6
# \ \ /
# 7 9 10
#
# 二叉树节点列表为(完美对齐):
# node: val left right
# Node00: 00, Node01, Node02
# Node01: 01, Node03, Node04
# Node02: 02, Node05, Node06
# Node03: 03, None, Node07
# Node04: 04, None, Node09
# Node05: 05, None, None
# Node06: 06, Node10, None
# None : None, None, None
# Node07: 07, None, None
# None : None, None, None
# Node09: 09, None, None
# None : None, None, None
# None : None, None, None
# Node10: 10, None, None
#
# 进程已结束,退出代码0

  

Python 实现列表与二叉树相互转换并打印二叉树封装类-详细注释+完美对齐的更多相关文章

  1. Python 实现列表与二叉树相互转换并打印二叉树16-详细注释+完美对齐-OK

    # Python 实现列表与二叉树相互转换并打印二叉树16-详细注释+完美对齐-OK from binarytree import build import random # https://www. ...

  2. python中列表元组字符串相互转换

    python中有三个内建函数:列表,元组和字符串,他们之间的互相转换使用三个函数,str(),tuple()和list(),具体示例如下所示: >>> s = "xxxxx ...

  3. python 字符串,列表,元组,字典相互转换

    1.字典 dict = {'name': 'Zara', 'age': 7, 'class': 'First'} 字典转为字符串,返回:<type 'str'> {'age': 7, 'n ...

  4. 剑指offer:按之字形顺序打印二叉树(Python)

    题目描述 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推. 解题思路 先给定一个二叉树的样式: 前段时间 ...

  5. 【剑指Offer】从上往下打印二叉树 解题报告(Python)

    [剑指Offer]从上往下打印二叉树 解题报告(Python) 标签(空格分隔): 剑指Offer 题目地址:https://www.nowcoder.com/ta/coding-interviews ...

  6. Python实现打印二叉树某一层的所有节点

    不多说,直接贴程序,如下所示 # -*- coding: utf-8 -*- # 定义二叉树节点类 class TreeNode(object): def __init__(self,data=0,l ...

  7. 剑指offer——python【第59题】按之子形顺序打印二叉树

    题目描述 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推. 解题思路 这道题其实是分层打印二叉树的进阶版 ...

  8. 剑指offer-顺序打印二叉树节点(系列)-树-python

    转载自  https://blog.csdn.net/u010005281/article/details/79761056 非常感谢! 首先创建二叉树,然后按各种方式打印: class treeNo ...

  9. 【剑指Offer】按之字形顺序打印二叉树 解题报告(Python)

    [剑指Offer]按之字形顺序打印二叉树 解题报告(Python) 标签(空格分隔): 剑指Offer 题目地址:https://www.nowcoder.com/ta/coding-intervie ...

随机推荐

  1. uni-app 中实现 onLaunch 异步回调后执行 onLoad 最佳实践

    前言 好久没写博客了,由于公司业务需要,最近接触uiapp比较多,一直想着输出一些相关的文章.正好最近时间富余,有机会来一波输出了. 问题描述 在使用 uni-app 开发项目时,会遇到需要在 onL ...

  2. v86.01 鸿蒙内核源码分析 (静态分配篇) | 很简单的一位小朋友 | 百篇博客分析 OpenHarmony 源码

    本篇关键词:池头.池体.节头.节块 内存管理相关篇为: v31.02 鸿蒙内核源码分析(内存规则) | 内存管理到底在管什么 v32.04 鸿蒙内核源码分析(物理内存) | 真实的可不一定精彩 v33 ...

  3. Hyperledger Fabric 智能合约开发及 fabric-sdk-go/fabric-gateway 使用示例

    前言 在上个实验 Hyperledger Fabric 多组织多排序节点部署在多个主机上 中,我们已经实现了多组织多排序节点部署在多个主机上,但到目前为止,我们所有的实验都只是研究了联盟链的网络配置方 ...

  4. 在C#中使用正则表达式最简单的方式

    更新记录 本文迁移自Panda666原博客,原发布时间:2021年5月11日. 在.NET中使用正则表达式与其他语言并无太大差异.最简单的使用就是使用Regex类型自带的静态方法. 注意:在.NET中 ...

  5. .NetCore实现图片缩放与裁剪 - 基于ImageSharp

    前言 (突然发现断更有段时间了 最近在做博客的时候,需要实现一个类似Lorempixel.LoremPicsum这样的随机图片功能,图片有了,还需要一个根据输入的宽度高度获取图片的功能,由于之前处理图 ...

  6. 在jupyternotebook中写C/C++

    在jupyter notebook中写C/C++,最大的好处就是不用写main()函数,直接调用写好的函数即可执行. #include<stdio.h> int sum(int a,int ...

  7. Museui 图标速览,再也不用担心网页打不开了

    更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/119328173

  8. linux服务器通过mailx邮件发送附件到指定邮箱

    shell脚本查询数据库#!/bin/bash HOSTNAME="数据库IP" PORT="端口" USERNAME="用户" PASSW ...

  9. Windows启动谷歌浏览器Chrome失败(应用程序无法启动,因为应用程序的并行配置不正确)解决方法

    目录 一.系统环境 二.问题描述 三.解决方法 一.系统环境 Windows版本 系统类型 浏览器Chrome版本 Windows 10 专业版 64 位操作系统, 基于 x64 的处理器 版本 10 ...

  10. Ubuntu系统iptables安全防护整改计划

    端口开放 默认防火墙是开放所有端口的,如果拿来做应用服务器,就很危险,所以要把防火墙用起来,只将需要的端口开放,ubuntu用的是iptables防火墙. iptables处理流程 iptables ...