python 树结构 包_树结构之嵌套列表法实现Python

除了队列,栈等数据结构,树也是另一种数据结构。最常见的树结构就是家谱了,从祖先开始,若干个儿子,孙子等等。文件系统也是树结构的应用之一。

树用递归的定义来说就是,树有一个根节点,然后(可有可无)有若干个分支(子树),每个子树其实也是一棵树,也有若干个子树。如果每个节点最多有两个分支,那就是二叉树,如果最多有n个分支,那就是n叉树。

我才用列表嵌套的方式实现了二叉树。从递归的形式上说树的列表形式是[根节点,左子树,右子树],而每个子树也是一棵树,所以每棵子树也是一个列表。

这样的话,初始化一棵树,即只有一个根节点,即[根节点,[],[]]的形式。def BinaryTree(r):

return [r, [], []]

12

然后有插入左子树的方法,插入左子树,要给出插入哪个节点的左子树,即有一个相对节点。而且插入左子树就是如果原始的左子树为空,那就直接插入列表。如果原始的左子树不是空,也就是把原来的左子树的列表直接替换掉,原始的左子树成为新的左子树的左子树。def insertLeft(root,newBranch):

# 先把原始的左子树取出来

t = root.pop(1)

# 判断原始左子树是否为空

if len(t) > 1:

root.insert(1,[newBranch,t,[]])

else:

root.insert(1,[newBranch, [], []])

return root123456789

插入右子树同理。def insertRight(root,newBranch):

t = root.pop(2)

if len(t) > 1:

root.insert(2,[newBranch,[],t])

else:

root.insert(2,[newBranch,[],[]])

return root1234567

然后就是获取这个树的根节点的值,比较简单,直接最外层的列表的第一个元素就是。修改根节点的值,直接索引赋值即可。def getRootVal(root):

return root[0]

def setRootVal(root,newVal):

root[0] = newVal12345

获取左子树,获取右子树,和上面一样,直接索引即可。def getLeftChild(root):

return root[1]

def getRightChild(root):

return root[2]12345

嵌套列表的形式实现树比较容易理解,容易查看树的逻辑出位置,变相的可视化吧。下面是整体的代码,测试一下。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(3)

insertLeft(r,4)

insertLeft(r,5)

insertRight(r,6)

insertRight(r,7)

l = getLeftChild(r)

print(l)

setRootVal(l,9)

print(r)

insertLeft(l,11)

print(r)

print(getRightChild(getRightChild(r)))

作者:qq_42907161

链接:https://blog.youkuaiyun.com/qq_42907161/article/details/108415902

来源:优快云

著作权归作者所有,转载请联系作者获得授权,切勿私自转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值