Skip to content

Instantly share code, notes, and snippets.

@AlexeiDarmin
Created November 17, 2018 23:39
Show Gist options
  • Save AlexeiDarmin/d5519597ceabb200aa44b98b5ec49b5f to your computer and use it in GitHub Desktop.
Save AlexeiDarmin/d5519597ceabb200aa44b98b5ec49b5f to your computer and use it in GitHub Desktop.
Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minial height.
// given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minial height.
class BinaryNode<T> {
data: T
leftChild: BinaryNode<T>
rightChild: BinaryNode<T>
constructor(data: T) {
this.data = data
}
}
function buildTree(lst: number[]) {
if (!lst || lst.length === 0) return null
if (lst.length === 1) return new BinaryNode(lst[0])
const medianIndex = Math.ceil((lst.length - 1) / 2)
const node = new BinaryNode(lst[medianIndex])
node.leftChild = buildTree(lst.slice(0, medianIndex))
node.rightChild = buildTree(lst.slice(medianIndex + 1, lst.length))
return node
}
console.log('build tree', buildTree([1,2,3,4,5,6,7,8]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment