Skip to content

Instantly share code, notes, and snippets.

@LiuJi-Jim
Created May 5, 2015 16:35
Show Gist options
  • Select an option

  • Save LiuJi-Jim/42e58793ade78bce6a0a to your computer and use it in GitHub Desktop.

Select an option

Save LiuJi-Jim/42e58793ade78bce6a0a to your computer and use it in GitHub Desktop.
中序遍历迭代器
var MidIterator = function(root) {
this.stack = [root];
this.__pushLeft(root);
};
MidIterator.prototype.__pushLeft = function(node) {
if (!node) return;
var left = node.left;
while (left) {
this.stack.push(left);
left = left.left;
}
};
MidIterator.prototype.next = function() {
var stack = this.stack;
if (stack.length === 0) {
return {
finished: true
}
}
var top = stack.pop();
if (top.right) {
stack.push(top.right);
this.__pushLeft(top.right);
}
return {
value: top.value,
finished: false
};
};
var iter = new MidIterator(root);
for (var it = iter.next(); !it.finished; it = iter.next()) {
console.log(it.value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment