Last active
September 19, 2024 05:33
-
-
Save Phryxia/49ac6c3256efdb6c8ee6a03c4f76e013 to your computer and use it in GitHub Desktop.
TypeScript implementation of tree traversing iterator
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
interface TreeNode<T> { | |
value: T | |
children?: TreeNode<T>[] | |
} | |
function preTraverse<T>(node: TreeNode<T>): IterableIterator<T> { | |
const stack = [{ node, index: -1 }] | |
return { | |
[Symbol.iterator]() { | |
return this | |
}, | |
next() { | |
while (stack.length) { | |
const top = stack[stack.length - 1] | |
if (top.index === -1) { | |
++top.index | |
return { value: top.node.value } | |
} | |
if (top.node.children && top.index < top.node.children.length) { | |
stack.push({ node: top.node.children[top.index++], index: -1 }) | |
} else { | |
stack.pop(); | |
} | |
} | |
return { value: undefined, done: true } | |
} | |
} | |
} | |
function postTraverse<T>(node: TreeNode<T>): IterableIterator<T> { | |
const stack = [{ node, index: 0 }] | |
return { | |
[Symbol.iterator]() { | |
return this | |
}, | |
next() { | |
while (stack.length) { | |
const top = stack[stack.length - 1] | |
if (top.node.children && top.index < top.node.children.length) { | |
stack.push({ | |
node: top.node.children[top.index], | |
index: 0, | |
}) | |
top.index++ | |
} else { | |
stack.pop() | |
return { value: top.node.value } | |
} | |
} | |
return { value: undefined, done: true } | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Note
Both implementation tries to consume minimum memory as possible as I can. They're implemented by me at first, then refined by Claude 3.5 sonnet.
In both case, they consume memory at most O(d) where d is the maximum depth of given tree. Note that there is no
children.reverse
to prevent pushing prematurely their children.