Python学习数据结构之(列表)树
2020-03-17 07:37
323 查看
列表之列表构成树
使用列表之列表和节点法都可以完成树的构建。
树是一种很常见的数据结构,它在维持算法的有序性上具有巨大作用。
列表法是基于[a,[],[]]这样的节点形式进行循环嵌套,维持相应的树结构。
话不多说上代码:
#建立二叉树 def BinaryTree(r): #节点格式: return [r,[],[]] #增加左字树 def insertLeft (root,newBranch): t = root.pop(1) #若当前节点有左子树存在则当前节点下沉,无则添加为左子树 if len(t) > 1: root.insert(1,[newBranch,t,[]]) else: root.insert(1,[newBranch,[],[]]) return root #新建右子树,方法同与左子树 def insertRight (root,newBranch): t = root.pop(2) if len(t)>1: root.insert(2,[newBranch,t,[]]) else: root.insert(2,[newBranch,[],[]]) return root #返回根节点 def getRootVal(root): return root[0] #重置根节点的值 def setRootVal(root,newVal): root[0] = newVal #获取左节点 def getLeftChild(root): return root[1] #获取右节点 def getRightChild(root): return root[2] r = BinaryTree(5) print(r) insertLeft(r,4) insertLeft(r,9) print(r) l = getLeftChild(r) print(l)
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- python数据结构之列表基本操作[学习笔记]
- Python学习之day3数据结构之列表
- Python中列表、字典、元组数据结构的简单学习笔记
- Python新手学习基础之数据结构-列表1
- Python学习笔记ucas(lecture2)数据结构(字符串、列表、元组、字典、集合)
- Python中列表、字典、元组数据结构的简单学习笔记
- python数据结构学习笔记-2016-10-24-02-使用排序列表实现集合ADT
- python数据结构学习笔记-2016-10-22-01-评价python列表
- Python基础学习之基本数据结构详解【数字、字符串、列表、元组、集合、字典】
- python数据结构学习笔记-2016-10-24-01-排序列表
- python数据结构学习笔记-2016-10-14-02-python列表
- 列表、元组、字典、引用的一些操作(数据结构)--python学习(3)
- Python学习笔记 - 基本数据结构:元组,列表,字典,集合
- 【python学习笔记】Python数据结构(列表,元组,字典,集合)
- 基础篇10-python基本数据结构-列表应用
- Python 学习1 之列表
- Python学习笔记3_列表和元组
- python数据结构学习笔记-1
- python数据结构学习记录
- Python学习笔记 —— List列表