Tree Implementation with Python

Tree Implementation with Python

List of List

代码如下:

def binary_tree(val):
    return [val, [], []]


def insert_left(root, val):
    root[1] = binary_tree(val)


def insert_right(root, val):
    root[2] = binary_tree(val)


def get_root_val(root):
    return root[0]


def set_root_val(root, val):
    root[0] = val


def get_left_child(root):
    return root[1]


def get_right_child(root):
    return root[2]


def preorder(root):
    if root:
        print(get_root_val(root))
        preorder(get_left_child(root))
        preorder(get_right_child(root))


def inorder(root):
    if root:
        inorder(get_left_child(root))
        print(get_root_val(root))
        inorder(get_right_child(root))


def postorder(root):
    if root:
        postorder(get_left_child(root))
        postorder(get_right_child(root))
        print(get_root_val(root))


if __name__ == '__main__':
    root = binary_tree('a')
    insert_left(root, 'b')
    insert_right(root, 'c')
    insert_right(get_left_child(root), 'd')
    insert_left(get_right_child(root), 'e')
    insert_right(get_right_child(root), 'f')
    print(root)
    # ['a',
    #     ['b',
    #         [],
    #         ['d', [], []]],
    #     ['c',
    #         ['e', [], []],
    #         ['f', [], []]]]

    preorder(root)  # a b d c e f
    inorder(root)  # b d a e c f
    postorder(root)  # d b e f c a

posted @   健康平安快乐  阅读(137)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2017-07-05 《踏踏实实学英语》读书笔记
点击右上角即可分享
微信分享提示