Python 实现列表与二叉树相互转换并打印二叉树封装类-详细注释+完美对齐
# 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 实现列表与二叉树相互转换并打印二叉树封装类-详细注释+完美对齐的更多相关文章
- Python 实现列表与二叉树相互转换并打印二叉树16-详细注释+完美对齐-OK
# Python 实现列表与二叉树相互转换并打印二叉树16-详细注释+完美对齐-OK from binarytree import build import random # https://www. ...
- python中列表元组字符串相互转换
python中有三个内建函数:列表,元组和字符串,他们之间的互相转换使用三个函数,str(),tuple()和list(),具体示例如下所示: >>> s = "xxxxx ...
- python 字符串,列表,元组,字典相互转换
1.字典 dict = {'name': 'Zara', 'age': 7, 'class': 'First'} 字典转为字符串,返回:<type 'str'> {'age': 7, 'n ...
- 剑指offer:按之字形顺序打印二叉树(Python)
题目描述 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推. 解题思路 先给定一个二叉树的样式: 前段时间 ...
- 【剑指Offer】从上往下打印二叉树 解题报告(Python)
[剑指Offer]从上往下打印二叉树 解题报告(Python) 标签(空格分隔): 剑指Offer 题目地址:https://www.nowcoder.com/ta/coding-interviews ...
- Python实现打印二叉树某一层的所有节点
不多说,直接贴程序,如下所示 # -*- coding: utf-8 -*- # 定义二叉树节点类 class TreeNode(object): def __init__(self,data=0,l ...
- 剑指offer——python【第59题】按之子形顺序打印二叉树
题目描述 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推. 解题思路 这道题其实是分层打印二叉树的进阶版 ...
- 剑指offer-顺序打印二叉树节点(系列)-树-python
转载自 https://blog.csdn.net/u010005281/article/details/79761056 非常感谢! 首先创建二叉树,然后按各种方式打印: class treeNo ...
- 【剑指Offer】按之字形顺序打印二叉树 解题报告(Python)
[剑指Offer]按之字形顺序打印二叉树 解题报告(Python) 标签(空格分隔): 剑指Offer 题目地址:https://www.nowcoder.com/ta/coding-intervie ...
随机推荐
- 第06组Alpha冲刺(6/6)
目录 1.1 基本情况 1.2 冲刺概况汇报 1.郝雷明 2.曹兰英 3. 方梓涵 4.曾丽莉 5.鲍凌函 6.杜筱 7.黄少丹 8.詹鑫冰 9.董翔云 10.吴沅静 1.3 冲刺成果展示 1.1 基 ...
- python封装发送邮件类
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart i ...
- Python工程:ImportError: attempted relative import with no known parent package
Python工程:ImportError: attempted relative import with no known parent package 解决方法: 1.对每个目录创建的时候都选择创建 ...
- 充电log关键词
充电LOG 1.healthd 2.暗码log 1.healthd healthd:battery l=96 v=4378 t=20.0 h=2 st=3 c=55 fc=4709000 cc=15 ...
- Datax源码改造关键步骤记录
Datax源码改造关键步骤记录: 一.作业配置1.一个job配置:reader 和writer 的column 字段必须是所有表共有的:2.reader多张表,writer一个表时,所有reader的 ...
- jenkins 自动化部署vue前端+java后端项目 进阶一
今天又不想写了,那么我来将我参考的文章直接分享给大家好了,大家也可以直接进行参考: 这里以centos7为例搭建自动化部署项目: 1.搭建部署前端服务代理nginx: 借鉴于:https://blog ...
- atcoder abc 244
atcoder abc 244 D - swap hats 给定两个 R,G,B 的排列 进行刚好 \(10^{18}\) 次操作,每一次选择两个交换 问最后能否相同 刚好 \(10^{18}\) 次 ...
- 在C#中使用正则表达式最简单的方式
更新记录 本文迁移自Panda666原博客,原发布时间:2021年5月11日. 在.NET中使用正则表达式与其他语言并无太大差异.最简单的使用就是使用Regex类型自带的静态方法. 注意:在.NET中 ...
- 彰显个性│制作一个独一无二的动态 svg 头像
一.头像预览 看一下博主的动态图像,是不是很炫酷,想不想拥有一个? 这是一个 svg 图片,svg 图片不仅可以通过制图软件制作外,其实也可以通过代码进行开发 因为 svg 本质上是一个下 xml 文 ...
- JavaScript中DOM查询封装函数
在JavaScript中可以通过BOM查询html文档中的元素,也就是所谓的在html中获取对象然后对它添加一个函数. 常用的方法有以下几种: ①document.getElementById() 通 ...