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]


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', [], []]]]

猜你喜欢

转载自www.cnblogs.com/fengyubo/p/9267260.html