zoukankan      html  css  js  c++  java
  • 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
    
    
  • 相关阅读:
    UVa11324 最大团
    UVa11624 BFS
    UVa10047 BFS
    UVa11054 欧拉回路
    CF413B 水题
    UVa LA 4287 强连通 (类似 hdu 3836)
    hdu1540 线段树(区间合并)
    最少的扇形区域 ——贪心
    Little Busters! — 并查集
    筛1-n中每个数的因子(nlogn)
  • 原文地址:https://www.cnblogs.com/fengyubo/p/9267260.html
Copyright © 2011-2022 走看看