class TreeNode:
"""
节点类
"""
def __init__(self):
self.data = None
self.childrenList = []
def AddChildNode(self, tNode):
"""
给当前节点添加子节点
"""
self.childrenList.append(tNode)
class Tree:
"""
树类
"""
def __init__(self, maxNodes):
self.root = None
self.nodes = [TreeNode() for _ in range(maxNodes)]
def GetTreeNode(self, id):
"""
根据节点索引获取节点
"""
return self.nodes[id]
def SetRoot(self, rootId):
"""
设置树的根节点
"""
self.root = self.GetTreeNode(rootId)
def AddChild(self, parentId, sonId):
"""
根据父节点的id代表的节点添加子节点id代表的节点
"""
pNode = self.GetTreeNode(parentId)
sNode = self.GetTreeNode(sonId)
pNode.AddChildNode(sNode)
def AssignData(self, nodeId, data):
"""
给指定节点id的节点设置数据
"""
self.GetTreeNode(nodeId).data = data
def Print(self, node=None):
"""
根据深度优先算法打印输出树的数据
"""
if node == None:
node = self.root
print(node.data, end='')
for i in node.childrenList:
self.Print(i)
def test():
t = Tree(9)
t.SetRoot(0)
t.AssignData(0, 'a')
t.AssignData(1, 'b')
t.AssignData(2, 'c')
t.AssignData(3, 'd')
t.AssignData(4, 'e')
t.AssignData(5, 'f')
t.AssignData(6, 'g')
t.AssignData(7, 'h')
t.AssignData(8, 'i')
t.AddChild(0,1)
t.AddChild(0,2)
t.AddChild(1,3)
t.AddChild(3,6)
t.AddChild(3,7)
t.AddChild(3,8)
t.AddChild(2,4)
t.AddChild(2,5)
t.Print()
test()
python实现抽象数据类型=>树
最新推荐文章于 2024-11-15 10:17:44 发布