Converting Recursive Traversal to Iterator
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的更多相关文章
- Java性能提示(全)
http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...
- HashMap与TreeMap源码分析
1. 引言 在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Ja ...
- java.util.Map源码分析
/** * An object that maps keys to values. A map cannot contain duplicate keys; * each key can map to ...
- [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 ...
- jdk1.8新特性之接口default方法
众所周知,default是java的关键字之一,使用场景是配合switch关键字用于条件分支的默认项.但自从java的jdk1.8横空出世以后,它就被赋予了另一项很酷的能力——在接口中定义非抽象方法. ...
- java面试基础篇(一)
最近想深入的理解一下java 的工作机制,也是便于后期的面试. 1.A:HashMap和Hashtable有什么区别? Q:HashMap和Hashtable都实现了Map接口,因此很多特性非常相似. ...
- 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. ...
- Java的集合(一)
转载:https://blog.csdn.net/hacker_zhidian/article/details/80590428 Java集合概况就三个:List.set和map list(Array ...
- Tree 使用方式
Traditional Ways of Tree Traversal This page contains examples of some “standard” traversal algorith ...
随机推荐
- sqlserver2017 SSAS配置远程访问不成功的问题
sqlserver2017 SSAS通过IIS配置远程访问一直访问不成功的解决办法: 出现这个问题的原因从微软给出的更新包中说的就是: 从 SQL Server 2017 开始,Analysis Se ...
- Redis:MySQL算老几?
原创: 码农翻身刘欣 前言:上一篇<MySQL:缓存算什么东西?>里挖了一个坑,也有很多人说没看过瘾,今天接着写,把坑填上,不过得把视角换一下,让Redis上台发言. 我知道MySQL看我 ...
- Subplot 多合一显示
1.均匀图中图 matplotlib 是可以组合许多的小图, 放在一张大图里面显示的. 使用到的方法叫作 subplot. 使用import导入matplotlib.pyplot模块, 并简写成plt ...
- 如何让 curl 命令通过代理访问
如何让 curl 命令通过代理访问 Linux.中国 - 开源中文社区 2018-01-18 8909 阅读 技术 我的系统管理员给我提供了如下代理信息: IP: 202.54.1.1 Port: 3 ...
- HTML5学习路线导航
一.基本标签元素 1.基础标签第一篇 2.基础标签第二篇 3.表单form的使用 4.新增表单验证 二.CSS样式表 4.CSS插入样式表的三种格式 5.六大选择器 6.样式内容详细讲解 7.背景渐进 ...
- openwrt添加内核模块
进行目录package/kernel mkdir url-redirect cd url-redirect [zzh@KD1 url-redirect]$ tree . |-- Makefile `- ...
- N2N windows下编译安装文件
n2n安装 n2n原理编译版下载,可直接使用:windows下vpn客户端 n2n_v2_linux_x64 n2n_v2_Win32TAP网卡驱动 #linux环境编译yum install -y ...
- ftp协议 主动和被动两种模式模式
- 运用SharedPreferences“偷取”输入的信息
运用SharedPreferences"偷取"输入的信息 本次的任务是 利用SharedPreferences来完成信息的保存和读取 就是你输入什么 手机就可以把输入的内容&quo ...
- Transform(变换)—Y轴lable内容旋转
<!DOCTYPE html> <html> <head> <style> div{ border:1px solid; } .bb{ position ...