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 ...
随机推荐
- unity---摄像机参数
2D游戏一般选择填充,减少性能浪费,也一般选择正交模式 Fiel of View 类似望远镜的效果 Clipping Planes 摄像机开始摄像和结束,两个平面的位置 Depth 决定摄像头的优先级 ...
- Ubuntu的一些软件源
参考别人的,自己记录一下,怕丢失 修改方法:vim /etc/apt/sources.list,然后添加下面对应的代码区 台湾的官方源 deb http://tw.archive.ubuntu.com ...
- Python模块Ⅱ
Python模块2 part3 模块的分类: 内置模块200种左右:python自带的模块,time os sys hashlib等 第三方模块6000种左右:需要pip install beauti ...
- USACO 刷题小记
\(\text{High Card Low Card}\) USACO2015DEC Platinum T2 贝西和艾尔西在玩游戏.有 \(2n\) 张牌,牌上的数字是 \(1\) 到 \(2n\) ...
- Python列表推导式,字典推导式,元组推导式
参考:https://blog.csdn.net/A_Tu_daddy/article/details/105051821 my_list = [ [[1, 2, 3], [4, 5, 6]] ] f ...
- Spring Security整合企业微信的扫码登录,企微的API震惊到我了
本文代码: https://gitee.com/felord/spring-security-oauth2-tutorial/tree/wwopen/ 现在很多企业都接入了企业微信,作为私域社群工具, ...
- Linux/Ubuntu 安装Redis
更新记录 2022年6月15日 发布. 2022年6月12日 开始编写. 安装Redis 更新源 sudo apt update 安装redis sudo apt install redis-serv ...
- 送分题,ArrayList 的扩容机制了解吗?
1. ArrayList 了解过吗?它是啥?有啥用? 众所周知,Java 集合框架拥有两大接口 Collection 和 Map,其中,Collection 麾下三生子 List.Set 和 Queu ...
- SAP -熟练使用T-Code SHD0
SHD0 业务顾问和开发顾问都非常熟悉的一个T-Code, 如果能合理使用它,可以省去许多增强和程序修改工作. 当我需要时,我在这里找不到任何相关文档,这就是为什么我想借此机会向我们自己的SCN提供内 ...
- linux函数与数组
1. 函数的定义 方法1: function_name () { statement } 方法2: function function_name () { statement } --先定义后使用 例 ...