Published
Edited
Jul 18, 2021
Insert cell
Insert cell
Insert cell
class ThreadedBinaryTree {
constructor (entry, left=null, right=null) {
[this.entry,this.left,this.right] = [entry,left,right]
}
*inorder () {
if (this.left && !this.left.isThread) yield* this.left.to.inorder()
yield this;
if (this.right && !this.right.isThread) yield* this.right.to.inorder()
}
thread () {
let a = [...this.inorder()];
for (let i = 0; i < a.length; i++) {
if (i > 0 && !a[i].left) a[i].left = new Link(a[i-1], true);
if (i+1 < a.length && !a[i].right) a[i].right = new Link(a[i+1], true);
}
return this
}
inorderSuccessor () {
let u = this.right;
if (!u) return null;
if (u.isThread) return u.to;
while (u.to.left && !u.to.left.isThread) {
u = u.to.left
}
if (u) return u.to
return null
}
inorderPredecessor () {
let u = this.left;
if (!u) return null;
if (u.isThread) return u.to;
while (u.to.right && !u.to.right.isThread) {
u = u.to.right
}
if (u) return u.to
return null
}
}
Insert cell
Insert cell
L = (to) => to ? new Link(to) : null
Insert cell
TBT = (e,l,r) => new ThreadedBinaryTree (e, L(l), L(r))
Insert cell
Insert cell
tbt1 = TBT("a",TBT("b",TBT("d", TBT("g"),TBT("h"))),TBT("c",TBT("e",null,TBT("i")),TBT("f"))).thread()
Insert cell
[...tbt1.inorder()].map(x => x.entry)
Insert cell
tbt1.inorderSuccessor().inorderSuccessor().inorderSuccessor()
Insert cell
tbt1.inorderPredecessor().inorderPredecessor().inorderPredecessor()
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more