您的位置:首页 > 理论基础 > 数据结构算法

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)

  • 点赞
  • 收藏
  • 分享
  • 文章举报
ldj0330 发布了12 篇原创文章 · 获赞 3 · 访问量 173 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: