DEV Community

gagecantrelle
gagecantrelle

Posted on

The Basics of a Binary Tree (Javascript)

When coding we would have some lines of code that would support each other. These sometimes are in random areas of our code. Making our code a bit messy to read and understand. By putting those lines of code into a binary tree our code will become clean. The binary tree is like
a family tree. It holds all information from the parent code to the child code allowing the developer to make complex lines of code.

The binary tree was studied by a man called Cayley. At the time it was seen as a math concept for graphs. Cayley stopped the reachers in 1857 then a man named McKay continued it (unable to find any information on McKay full name and the date when the teacher started again). He later discovered that the binary tree can be used in a database. Because the Binary tree is a concept and not a function, it can be used in any version of any coding language. There is no need to download any extra software to use it.

To use a binary tree you would
First, create an object and give it some values.

const obj = {
name: bob,
age: 1
} 
Enter fullscreen mode Exit fullscreen mode

Second, give the object another value that is an object or array. for now, let's look at the object version.

That new object added in should hold a similar value to the object in it

const obj = {
name: bob,
age: 1,
kids: {
name: bob,
age: 1,
kids: {}
}
}
Enter fullscreen mode Exit fullscreen mode

.Third, create a function that can loop through the binary tree using recursion. since it will be tricky to access some of the data.

function recursion(obj, target)=>{
if(obj.name === target){
 return True;
}else if(Object.keys(obj).length === 0){
return false
}

return recursion(obj.kids, target);
}

//this should just loop through the given object and return true if
//it finds the target or false if it doesn't find the target

Enter fullscreen mode Exit fullscreen mode

This should just loop through the given object and return true if it finds the target or false if it doesn't find the target. One way to use a Binary tree is to store information about your family. Like who are your parents, grandparents, siblings, your kids, your grandchild, and etc. And, with their information about the time when they were born to when they died.
Image description

Another way is to use it for video game enemies. When writing code for an enemy you may realize that two of the enemies look and act the same. So instead of copying the same code from one enemy to another. You can make one enemy the parent and the other one
the child. The child will have the same code as the parent.
Image description

the second screens shot is edited in gimp
//links
https://www.ukessays.com/essays/english-language/history-and-introduction-of-binary-trees-english-language-essay.php
https://www.cetconnect.org/how-to-make-your-own-family-tree/

Top comments (0)