In this article, I'm going to introduce a general pattern named Lazy Iterator for converting recursive traversal to iterator. Let's start with a familiar example of inorder traversal of binary tree.

It is straightforward to write a recursive function which returns the nodes as List:

// Java
List<Node> traverseInOrder(Node node) {
if (node == null) {
return emptyList();
}
Return concat(traverseInOrder(node.left), List.of(node), traverseInOrder(node.right));
} List<T> concat(List<T>... lists) {
... // List concatenation.
}

Of course, we can simply return the iterator of the result list, but the drawback is twofold: 1) it is not lazily evaluated, which means even if we only care about the first a few items, we must traverse the whole tree. 2) the space complexity is O(N), which is not really necessary. We'd like to have an iterator which is lazily evaluated and takes memory only as needed. The function signature is given as below:

// Java
Iterator<Node> traverseInOrder(Node node) {
// TODO
}

One idea most people could easily come up with (but not necessarily be able to correctly implement) is to use a stack to keep track of the state of traversal. That works, but it is relatively complex and not general, there is a neat, simple and general way. This is the code which demonstrates the pattern:

// Java
Iterator<Node> traverseInOrder(Node node) {
if (node == null) {
return emtpyIterator();
}
Supplier<Iterator<Node>> leftIterator = () -> traverseInOrder(node.left);
Supplier<Iterator<Node>> currentIterator = () -> singleNodeIterator(node);
Supplier<Iterator<Node>> rightIterator = () -> traverseInOrder(node.right);
return concat(leftIterator, currentIterator, rightIterator);
} Iterator<T> concat(Supplier<Iterator<T>>... iteratorSupplier) {
// TODO
}

If you are not familiar with Java, Supplier<T> is a function which takes no argument and returns a value of type T, so basically you can think of it as a lazily evaluated T.

Note the structural correspondence between the code above and the original recursive traversal function. Instead of traverse the left and right branches before returning, it creates a lambda expression for each which when evaluated will return an iterator. So the iterators for the subproblems are lazily created.

Finally and the most importantly, it needs the help of a general function concat which creates an iterator backed by multiple iterator suppliers. The type of this function is (2 suppliers):

Supplier<Iterator<T>> -> Supplier<Iterator<T>> -> Iterator<T>

The key is that this function must keep things lazy as well, evaluate only when necessary. Here is how I implement it:

// Java
Iterator<T> concat(Supplier<Iterator<T>>... iteratorSuppliers) {
return new LazyIterator(iteratorSuppliers);
} class LazyIterator<T> {
private final Supplier<Iterator<T>>[] iteratorSuppliers;
private int i = 0;
private Iterator<T> currentIterator = null; public LazyIterator(Supplier<Iterator<T>>[] iteratorSuppliers) {
this.iteratorSuppliers = iteratorSuppliers;
} // When returning true, hasNext() always sets currentIterator to the correct iterator
// which has more elements.
@Override
public boolean hasNext() {
while (i < iteratorSuppliers.length) {
if (currentIterator == null) {
currentIterator = iteratorSuppliers[i].apply();
}
if (currentIterator.hasNext()) {
return true;
}
currentIterator = null;
i++;
}
return false;
} @Override
public T next() {
return currentIterator.next();
}
}

The LazyIterator class works only on Iterator<T>, which means it is orthogonal to specific recursive functions, hence it serves as a general way of converting recursive traversal into iterator.

If you are familiar with languages with generator, e.g., Python, the idiomatic way of implementing iterator for recursive traversal is like this:

# Python
def traverse_inorder(node):
if node.left:
for child in traverse_inorder(node.left):
yield child
yield node
if node.right:
for child in traverse_inorder(node.right):
yield child

yield will save the current stack state for the generator function, and resume the computation later when being called again. You can think of the lazy iterator pattern introduced in this article as a way of capturing the computation which can be resumed, hence simulate the generator feature in other languages.

Converting Recursive Traversal to Iterator的更多相关文章

  1. Java性能提示(全)

    http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...

  2. HashMap与TreeMap源码分析

    1. 引言     在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Ja ...

  3. java.util.Map源码分析

    /** * An object that maps keys to values. A map cannot contain duplicate keys; * each key can map to ...

  4. [leetcode]428. Serialize and Deserialize N-ary Tree序列化与反序列化N叉树

    Serialization is the process of converting a data structure or object into a sequence of bits so tha ...

  5. jdk1.8新特性之接口default方法

    众所周知,default是java的关键字之一,使用场景是配合switch关键字用于条件分支的默认项.但自从java的jdk1.8横空出世以后,它就被赋予了另一项很酷的能力——在接口中定义非抽象方法. ...

  6. java面试基础篇(一)

    最近想深入的理解一下java 的工作机制,也是便于后期的面试. 1.A:HashMap和Hashtable有什么区别? Q:HashMap和Hashtable都实现了Map接口,因此很多特性非常相似. ...

  7. Java-Class-I:java.util.Map

    ylbtech-Java-Class-I:java.util.Map 1.返回顶部 1.1. import java.util.HashMap; import java.util.Map; 1.2. ...

  8. Java的集合(一)

    转载:https://blog.csdn.net/hacker_zhidian/article/details/80590428 Java集合概况就三个:List.set和map list(Array ...

  9. Tree 使用方式

    Traditional Ways of Tree Traversal This page contains examples of some “standard” traversal algorith ...

随机推荐

  1. vue 配置了全局的http拦截器,单独某个组件不需要这个拦截器,如何设置

    之前写过关于全局配置http拦截器的随笔,现在有个需求,在微信支付时,生成二维码,页面显示一个遮罩层,二维码页面需要每两秒请求一次接口,若返回结果为已支付,则进行页面跳转,但因为全局http中load ...

  2. shp2pgsql向postgresql导入shape数据

    1. 准备好Shape文件(不仅仅是.shp文悠扬,还要有其他相关数据文件,包括.shx..prj..dbf文件). 2. 使用命令将Shape数据转换为*.sql文件 shp2pgsql -s 38 ...

  3. nginx集成环境下载

    https://visual-nmp.en.softonic.com/download

  4. PlayFramework 一步一步来 之 页面模板引擎

    Play的魔板引擎本人认为可以说是为full stack Developers量身打造的功能.在原有的html页面基础上,只需要在html文件名后缀名前面加上”.scala“,就可以在页面上写Scal ...

  5. graph_base_pic_segmentation里面的细节和代码

    https://github.com/zhangbo2008/graph_base_pic_segmentation_analyzing/blob/master/README.md

  6. AJAX随笔1

    [1] AJAX简介   > 全称: Asynchronous JavaScript And XML   > 异步的JavaScript和XML   > AJAX就是通过JavaSc ...

  7. Scrapy爬虫框架的学习

    第一步安装 首先得安装它,我使用的pip安装的 因为我电脑上面安装了两个python,一个是python2.x,一个是python3.x,所以为了区分,所以,在cmd中,我就使用命令:python2 ...

  8. Spring Ioc 常用注解

    在开发中spring ioc的配置方式有多种方式,常用的一般都是byName.byType .以及其自动装配可以查看http://www.cnblogs.com/gubai/p/9140840.htm ...

  9. squid代理加用户认证

    squid代理加用户认证 用authentication helpers添加身份验证 有如下几种认证方式 :=> NCSA: Uses an NCSA-style username and pa ...

  10. 20155312张竞予 Exp1 PC平台逆向破解(5)M

    Exp1 PC平台逆向破解(5)M 目录 实验内容 手工修改可执行文件,改变程序执行流程,直接跳转到getShell函数. 利用foo函数的Bof漏洞,构造一个攻击输入字符串,覆盖返回地址,触发get ...