Skip to main content

Binary Search Tree

We start searching for a key from the root until we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node.

insert
export class BinaryNode {
left: BinaryNode | null = null
right: BinaryNode | null = null

constructor(public data: number) {}

insert(data: number): boolean {
if (data === this.data) {
return false
}

const isGoLeft = data < this.data
const next = isGoLeft ? this.left : this.right

if (next === null) {
const newNode = new BinaryNode(data)
if (isGoLeft) {
this.left = newNode
} else {
this.right = newNode
}

return true
}

return next.insert(data)
}
}