栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

树的存储和遍历——python实现前,中,后序遍历

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

树的存储和遍历——python实现前,中,后序遍历

# 该方式表明只有存在左子树才可能有右子树,而右子树不会单独存在
class TreeNode:  # 定义孩子节点
    def __init__(self, val):
        # 存储某个节点在表头数组的下标
        self.child = val
        # 指向该头节点的下一个孩子
        self.next = None


class HeadNode:  # 定义表头结点
    def __init__(self, val):
        # 数据域:相当于该节点代表的值
        self.data = val
        # 指针域指向该节点第一个孩子节点
        self.firstchild = None  # 将其指向TreeNode


# 先初始化多个表头结点,0也代表了初始化每个节点的data为0
headNode = [HeadNode(0) for i in range(100)]


def add(a, b):  # 我们使b作为a的孩子节点,所以要先创建b
    tree_node = TreeNode(b)  # 该孩子节点的child编号为b
    if headNode[a].firstchild != None:  # 表示a节点存在左孩子节点
        headNode[a].firstchild.next = tree_node
    else:
        headNode[a].firstchild = tree_node  # 否则将b节点置为右孩子节点


# 后序遍历
def dfs(x):
    x = int(x)
    temp_treeNode = headNode[x].firstchild  # 临时节点,指向以n为根的子树的左子树
    if temp_treeNode != None:  # 说明存在左子树
        dfs(temp_treeNode.child)
        temp_treeNode = temp_treeNode.next  # 再去看右子树
        if temp_treeNode != None:  # 说明有右子树
            dfs(temp_treeNode.child)
        print(headNode[x].data, end=' ')#(根)
    else:
        print(headNode[x].data, end=' ')

# 前序遍历
# def dfs(x):
#     x = int(x)
#     temp_treeNode = headNode[x].firstchild  # 临时节点,指向以n为根的子树的左子树
#     print(headNode[x].data, end=' ')
#     if temp_treeNode != None:  # 说明存在左子树
#         dfs(temp_treeNode.child)
#         temp_treeNode = temp_treeNode.next  # 再去看右子树
#         if temp_treeNode != None:  # 说明有右子树
#             dfs(temp_treeNode.child)

# 中序遍历
# def dfs(x):
#     temp_treeNode = headNode[x].firstchild  # 临时节点,指向x为根的节点的左子树
#     if temp_treeNode != None:  # 存在左子树时
#         dfs(temp_treeNode.child)  # 参数为左子树节点编号
#         print(headNode[x].data, end=' ')  # (根)
#         temp_treeNode = temp_treeNode.next
#         if temp_treeNode != None:  # 存在右子树时
#             dfs(temp_treeNode.child)
#     else:
#         print(headNode[x].data, end=' ')


if __name__ == '__main__':
    n = int(sys.stdin.readline())
    data = sys.stdin.readline().split()
    for i in range(n):
        headNode[i + 1].data = data[i]  # 重新给每个节点的data赋值
    for i in range(n - 1):
        a, b = map(int, sys.stdin.readline().split())
        add(a, b)  # 将a,b节点连接
    root = int(sys.stdin.readline())
    dfs(root)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/971405.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号