Tree Implementation with Python Tree Implementation with Python

List of List

Tree Implementation with Python
Tree Implementation with Python

代码如下:

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