Binary tree traversal with iterator

Ujjwal Gupta
Dec 30, 2020

In this article- I am going to write a program which will use javascript generators to traverse a binary tree.

class Node {
constructor(value) {
this.data = value;
}
}
class BinaryTree {
constructor() {
this.root = new Node(5);
this.root.left = new Node(10);
this.root.right = new Node(20);
}
* start() {
const root = this.root;
const stack = [root];
while (stack.length > 0) {
const node = stack.shift();
yield node.data;
if (node.left) {
stack.push(node.left)
}
if (node.right) {
stack.push(node.right)
}
}
}
}
const tree = new BinaryTree();
const iterator = tree.start();
let g = iterator.next();
while (!g.done) {
console.log("value", g.value);
g = iterator.next();
}

How about creating iterators without using default javascript generator. In this case you can push the yield element into another stack which will be used for iteration.

--

--

Ujjwal Gupta

Frontend lead Polygon | Creator of jsstore, mahaljs | sqlweb, fortjs | opensource creator | we3, blockchain, solidity | javascript