其他分享
首页 > 其他分享> > 数据结构——树

数据结构——树

作者:互联网

def  tree(root_label, branches = []):
    """定义一棵树,树根节点值,树的分支
    root_label: 根节点值
    branches: 分支,初始为空,只有根节点
    """
    for branch in branches:
#           遍历子树,每个子树都要是树
        assert is_tree(branch), 'branches must be trees'
#     返回根节点+子树列表
    return [root_label] + list(branches)


def label(tree):
    # 索引为0的为根节点
    return tree[0]

def branches(tree):
    #  索引1后为子树
    return tree[1:]

def is_tree(tree):
#     输入一颗树,判断是不是树, 即树需要是列表,并且长度大于1
    if type(tree) != list or len(tree) < 1:
        return False
    for branch in branches(tree):
#         检查子树是不是树
        if not is_tree(branch):
            return False
    return True

def is_leaf(tree):
#     判断一棵树是不是叶子节点, 如果不算子树,则是叶子节点
    return not branches(tree)
        
def fib_tree(n):
#     n:根节点值
    if n == 0 or n == 1:
        return tree(n)
    else:
        left, right = fib_tree(n - 2), fib_tree(n - 1)
#         n号节点值为n-1号和n-2号之和
        fib_n = label(left) + label(right)
#         tree(父节点值,子树)
        return tree(fib_n, [left, right])

def count_leaves(tree):
#     是叶子节点就返回1
    if is_leaf(tree):
        return 1
    else:
#     在每个子树里寻找叶子节点
        branch_counts = [count_leaves(branch) for branch in branches(tree)]
#     把子树里的叶子节点加起来
        return sum(branch_counts)

def partition_tree(n, m):
#     父节点值为0,树只有这一个节点,返回True
    if n == 0:
        return tree(True)
    elif n < 0 or m == 0:
        return tree(False)
    else:
#         左节点值为n - m
        left = partition_tree(n - m, m)
#         右节点值为m - 1 分割的n
        right = partition_tree(n, m - 1)
        return tree(m, [left, right])

def print_parts(tree, partition = []):
#     如果是叶子节点
    if is_leaf(tree):
#         如果该节点值不为0
#        递归基本条件:在叶子节点前加 + 输出, 
        if label(tree):
            print('+'.join(partition))
    else:
        left, right = branches(tree)
        m = str(label(tree))
        print_parts(left, partition + [m])
        print_parts(right, partition)

def left_binarize(tree):
    if is_leaf(tree):
        return tree
    if len(tree) > 2:
        tree = [tree[1:],tree[0]]
    return (left_binarize(branch) for branch in tree)

left_binarize([1,2,3,4,5,6,7])

标签:branches,tree,branch,return,数据结构,节点,def
来源: https://blog.csdn.net/Ennis_Tongji/article/details/113803319