python数据结构-树的列表展示

列表表示

        在由列表表示的树中,我们将从 Python 的列表数据结构开始,并编写上面定义的函数。虽然将接口作为一组操作在列表上编写与我们实现的其他抽象数据类型有点不同,但这样做是有趣的,因为它为我们提供了一个简单的递归数据结构,我们可以直接查看和检查。在列表树的列表中,我们将根节点的值存储为列表的第一个元素。列表的第二个元素本身将是一个表示左子树的列表。列表的第三个元素将是表示右子树的另一个列表。


myTree = [
    "a",  # root
    ["b",  # left subtree
     ["d", [], []], ["e", [], []]],
    ["c",  # right subtree
     ["f", [], []], []]
]

print(myTree)
print('left subtree = ', myTree[1])
print('root = ', myTree[0])
print('right subtree = ', myTree[2])

        树的根是 myTree[0] ,根的左子树是myTree[1] ,右子树是 myTree[2] 。 使用列表创建一个简单的树。一旦树被构建,我们可以访问根和左右子树。 该列表方法的一个非常好的属性是表示子树的列表的结构遵守树定义的结构; 结构本身是递归的!具有根值和两个空列表的子树是叶节点。列表方法的另一个很好的特性是它可以推广到一个有许多子树的树。在树超过二叉树的情况下,另一个子树只是另一个列表

建立一个tree_definition.py文件

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]

测试

from python_basic_tree.tree_definition_列表展示 import *

# 建立一个空树
tree = BinaryTree("")
print(tree)

# 插入根节点a
setRootVal(tree, "a")
print(tree)

# 建立以a为根节点,左右子树均为空的树
tree1 = BinaryTree("a")
print(tree1)

# 获得树的根节点
print(getRootVal(tree))
print(getRootVal(tree1))

# 树tree左子树插入b节点 ,左右子树均为空
insertLeft(tree, "b")
print(tree)

# 树tree右子树插入b节点 ,左右子树均为空
insertRight(tree, "c")
print(tree)

# 得到左子树
print(getLeftChild(tree))

# 得到右子树
print(getRightChild(tree))









猜你喜欢

转载自blog.csdn.net/qq_29286967/article/details/81010699