Treetarable is a lightweight and flexible library for working with binary tree data structures. It provides an elegant API for traversing, manipulating, and querying binary trees using modern JavaScript features like generators and iterators.
Note: This library is currently in development. Features and APIs may change in future releases.
- Generator-based traversal: Supports depth-first, breadth-first, pre-order, post-order, and default (in-order) traversal.
- Tree manipulation: Map, flatten and reduce tree nodes with ease.
- Node querying: Find nodes or paths based on custom predicates.
- Customizable iteration: Use built-in iterators or define your own.
Install the library via npm:
npm install treetarable
import { BinaryTree } from 'treetarable'
// Create a binary tree
const root = new BinaryTree(1)
root.left = new BinaryTree(2)
root.right = new BinaryTree(3)
root.left.left = new BinaryTree(4)
root.left.right = new BinaryTree(5)
for (const node of root) {
console.log(node.value) // 4, 2, 5, 1, 3
}
for (const node of root.bfIterator()) {
console.log(node.value) // 1, 2, 3, 4, 5
}
for (const node of root.preOrderIterator()) {
console.log(node.value) // 1, 2, 4, 5, 3
}
for (const node of root.postOrderIterator()) {
console.log(node.value) // 4, 5, 2, 3, 1
}
const newTree = root.map((value) => value * 2)
for (const node of newTree) {
console.log(node.value) // 8, 4, 10, 2, 6
}
const flatNodes = root.flat()
console.log(flatNodes.map((node) => node.value)) // [4, 2, 5, 1, 3]
const sum = root.reduce((acc, node) => acc + node.value, 0)
console.log(sum) // 15 (sum of all node values)
const foundNode = root.find((node) => node.value === 5)
console.log(foundNode?.value) // 5
const path = root.getPathOfNode((node) => node.value === 5)
if (path) {
for (const node of path.preOrderIterator()) {
console.log(node.value) // 1, 2, 5
}
}
root.forEach((node) => {
console.log(node.value) // 4, 2, 5, 1, 3
})
npm run build
npm run dev
npm run test
npm run lint
Contributions are welcome! If you have ideas for new features or improvements, feel free to open an issue or submit a pull request.
This project is licensed under the MIT License.