Whats is a Binary Tree

Woodelin florveus
3 min readSep 2, 2021

What are Trees?

When it comes to handling data structures and solving algorithms there’s a high chance you’ll run into Trees. This concept is complex and important in your Algorithms and Data Structure journey. We can start with Trees what are they? Trees are data structures where a node can have zero or more children. Similar to Graphs data structures the connections between the nodes are called edges. Of all names why are they called Trees? Believe it or not, the concept of the data structures resembles an actual tree. Starting off with the root node and branching with its descendants.

What are Binary Trees? Is it Similar to a Tree?

When a Tree has two children it is referred to as a Binary Tree. There a different sets of Binary. Depending on how the nodes are arranged in a Binary Tree it can be a Full, Complete, or Perfect Tree. You can read more below.

  1. Full Binary Tree — Each node has exactly 0 or 2 children (almost never 1)
  2. Complete Binary Tree — When all levels except one are full with nodes.
  3. Perfect Binary Tree — When all the levels including the last one are full of nodes.

Binary Search Trees? Why Should I Care?

Binary Search Trees or short BST are applications of Binary Trees. BST has at most two nodes similar to all Binary Trees. One interesting thing about the Binary Search Trees is the values. The left children’s value must be less than the parent, therefore the right children must be higher.

Here are some implementations below?

Starting with the root node

class Node {
constructor(value){
this.value = value
this.left = null
this.right = null
}
}
class Bst{
constructor(){
this.root = null
}

Insertion Method:

insert(value){
const newNode = new Node(value)
if (this.root === null){
this.root = newNode
return this
}
let temp = this.rootwhile(true){

if(newNode.value === temp.value) return undefined

if(newNode.value < temp.value){
if(temp.left === null){
temp.left = newNode
return this
}
temp = temp.left
} else {
if(temp.right === null){
temp.right = newNode
return this
}
temp = temp.right
}

}
}

Contains Method: Checking if the node exists in the tree

contains(value) {if(this.root === null) return falselet temp = this.rootwhile(temp){
if(value < temp.value){
temp = temp.left
} else if (value > temp.value){
temp = temp.right
} else {
return true
}
}
return false
}

Hope you guys enjoyed thanks for reading.

--

--