> Erlang中文手册 > balance/1 对树进行平衡操作

gb_trees:balance/1

对树进行平衡操作

用法:

balance(Tree1) -> Tree2

内部实现:

-spec balance(Tree1) -> Tree2 when
      Tree1 :: gb_tree(),
      Tree2 :: gb_tree().

balance({S, T}) ->
    {S, balance(T, S)}.

balance(T, S) ->
    balance_list(to_list_1(T), S).

balance_list(L, S) ->
    {T, []} = balance_list_1(L, S),
    T.

balance_list_1(L, S) when S > 1 ->
    Sm = S - 1,
    S2 = Sm div 2,
    S1 = Sm - S2,
    {T1, [{K, V} | L1]} = balance_list_1(L, S1),
    {T2, L2} = balance_list_1(L1, S2),
    T = {K, V, T1, T2},
    {T, L2};
balance_list_1([{Key, Val} | L], 1) ->
    {{Key, Val, nil, nil}, L};
balance_list_1(L, 0) ->
    {nil, L}.

对树 Tree1 进行重新平衡操作。这是一个很少需要用到的函数,但是当大量节点从树中被删除而之后没有往树里添加新数据时,那么调用这个函数是很有必要的。重新平衡的操作可以减少查找数据时的查询次数,因为删除操作不会对树进行重新平衡。

Tree1 = gb_trees:empty(),
Tree2 = gb_trees:enter(a, 1, Tree1),
gb_trees:balance(Tree2).