Published
Edited
Oct 3, 2022
1 star
Insert cell
# Let's make a binary search tree
Insert cell
function getRandomIntegers(count) {
const output = []
for (let i = 0; i < count; ++i) {
output.push(Math.ceil((Math.random() - 0.5) * 100))
}
return output
}
Insert cell
getRandomIntegers(15)
Insert cell
class Node {
constructor(value) {
this.value = value
this.left = null
this.right = null
this.children = []
}

insert (value) {
if (value === this.value) return;

if (value > this.value) {
if (this.right) {
this.right.insert(value)
} else {
this.right = new Node(value)
this.children.push(this.right)
}
} else if (value < this.value) {
if (this.left) {
this.left.insert(value)
} else {
this.left = new Node(value)
this.children.push(this.left)
}
}
}
}
Insert cell
root = new Node(getRandomIntegers(1)[0])
Insert cell
function insertRandomValues(node, count) {
for (let r of getRandomIntegers(12)) {
node.insert(r)
}
return node
}
Insert cell
insertRandomValues(root, 10)
Insert cell
import { Tree } from '@d3/tree'
Insert cell
Tree(root, {
label: d => d.value,
})
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