JSFiddle - React, Tailwind, and code Playground
by amirshim
JavaScript 1.7
// tree traversal and nth element
function Tree(value,left = null,right = null) {
return {left,value,right};
}
function* traverseTree(tree) {
if (tree) {
yield *traverseTree(tree.left);
yield tree.value;
yield *traverseTree(tree.right);
}
}
function* withIndex(otherIt) {
var count = 0;
for(var a of otherIt) {
yield [count, a];
count++;
}
}
var mytree = Tree(20, Tree(10), Tree(30));
var k = 2;
for(var a of withIndex(traverseTree(mytree))) {
if (a[0] == k) {
console.log(a[1]);
break;
}
}