树的存储和遍历——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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谁动了我的马卡龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值