> Erlang中文手册 > iterator/1 返回一个树的迭代器

gb_trees:iterator/1

返回一个树的迭代器

用法:

iterator(Tree) -> Iter

返回一个可以用来遍历整个树 Tree 的迭代器。这个函数的执行是很有效率的;使用 gb_trees:next/1 方法遍历整个树只比用 gb_trees:to_list/1 先把树里的所有元素转为列表再遍历稍微慢一些;迭代器的优势在于它不用每一次调用的时候把整个列表的所有元素都加载在内存里。

Orddict = orddict:from_list([{pear, 7}, {orange, 5}, {apple, 2}]),
Tree = gb_trees:from_orddict(Orddict),
Iterator = gb_trees:iterator(Tree),
gb_trees:next(Iterator).
Orddict = orddict:from_list([{pear, 7}, {orange, 5}, {apple, 2}]),
Tree = gb_trees:from_orddict(Orddict),
gb_trees:iterator(Tree).

Erlang 的通用平衡树 gb_trees 模块没有内置的遍历(fold)函数,不过可以利用迭代函数 gb_trees:iterator/1 和 gb_trees:next/1 来模拟遍历二叉树的功能。下面是遍历获取树里的每个键和值:

Orddict = orddict:from_list([{pear, 7}, {orange, 5}, {apple, 2}]),
Tree = gb_trees:from_orddict(Orddict),
GBTreesFold = fun GBTreesFold(AccIterator, AccList) ->
    case gb_trees:next(AccIterator) of
        none ->
            AccList;
        {Key, Val, NewAccIterator} ->
            GBTreesFold(NewAccIterator, [{Key, Val} | AccList])
    end
end,
Iterator = gb_trees:iterator(Tree),
GBTreesFold(Iterator, []).