Created
May 5, 2015 16:35
-
-
Save LiuJi-Jim/42e58793ade78bce6a0a to your computer and use it in GitHub Desktop.
中序遍历迭代器
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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