How To Implement Binary Search Tree In Javascript - letsbug

     Many times we required to have more than two paths from data object (non-linear) when we have to represent one or many relationship. The best way is to use non-linear data structure.

    Tree is a non-linear data structure. Non-linear  data structures are capable of expression more complex relationship than linear data structure. In general, wherever the hierarchical relationship among data is to be preserved tree is used.

    Today in this article we are going to implement a basic Binary Search Tree. But before that lets see a binary tree.

    What is a Binary Tree?

    Binary Tree is a special form of a tree is finite set of nodes, which is either empty or partitioned into three sets, one which is the root and two disjoint binary trees called left subtree and right subtree. It si a tree where every node can have at most two branches(children).

    Now lets implement 

Binary Search Tree in Javascript

First we create BinaryTree class which encapsulates our whole tree. And has all the main methods of the tree. We have only implemented two methods insert and traverse.

class BinaryTree{
    constructor(){
        this.root = null
    }
    insert(data){
        if(this.root == null){
            this.root = new Node(data)
        }else{
            this.root.addNode(new Node(data))
        }
    }
    traverse(){
        this.root.traverse()
    }
}

Then we have Node class which is the core of the BinaryTree class. All the data added into the tree is stored as a node into the BinaryTree. addNode and traverse are two methods of the Node class.

class Node{
    constructor(data){
        this.left = null
        this.right = null
        this.value = data
    }
    addNode(node){
        if(node.value < this.value){
            if(this.left == null){
                this.left = node
            }else{
                this.left.addNode(node)
            }
        }else if (node.value > this.value){
            if(this.right == null){
                this.right = node
            }else{
                this.right.addNode(node)
            }
        }
    }
    traverse(){
        if(this.left != null) this.left.traverse()
        console.log(this.value)
        if(this.right != null) this.right.traverse()
    }
}

Now that we have our classes done. Below we initialise binary tree as tree and add random number elements into it. And then we call the traverse method and print the tree.

let tree = new BinaryTree()

for(let i = 0; i < 20; i++){
    tree.insert(Math.ceil(Math.random(1) * 200))
}

tree.traverse()
console.log(tree)

Below is how we get the output.

3

6

21

34

60

63

73

78

105

113

140

143

148

156

172

175

189

196

BinaryTree {

  root: Node {

    left: Node { left: null, right: null, value: 3 },

    right: Node { left: [Node], right: null,

value: 196 },

    value: 6

  }

}


Thankyou

Comments

Categories

Big Data Analytics Binary Search Binary Search Tree Binary To Decimal binary tree Breadth First Search Bubble sort C Programming c++ Chemical Reaction and equation class 10 class 10th Class 9 Climate Complex Numbers computer network counting sort CSS Cyber Offenses Cyber Security Cyberstalking Data Science Data Structures Decimal To Binary Development diamond pattern Digital Marketing dust of snow Economics Economics Lesson 4 Email Validation English fire and ice Food Security in India Footprints Without feet Forest And Wildlife Resources game Geography Geography lesson 6 glassmorphism Glossary Graph HackerRank Solution hindi HTML image previewer India-Size And Location Insertion Sort Internet Network Status Interview Questions Introduction to cyber crime and cyber security IT javascript tricks json to CSV converter lesson 2 lesson 1 lesson 2 Lesson 3 Lesson 6 lesson 7 Life lines of National Economy life processes Linear Search Linked List lowest common ancestor Machine Learning MCQs median in array Merge sort min and max of two numbers Moment Money and Credit My Childhood Natural Vegetation and Wildlife NCERT Network connectivity devices Network Models Network Security No Men Are foreign Node.js operator overloading P5.js PHP Physical features of India Population Prime Numbers python Quick sort R language Rain on the roof Regular Expression Resources and development reversing array saakhi science Searching Algorithm Selection sort Social Media Marketing social science Software Engineering Software Testing Sorting Algorithm Stacks staircase pattern System Concepts Text Recognition The last Leaf time converter Time Passed From A Date Todo List App Tree Trending Technologies Understanding Economic Development username and password video player Visualization water resources Wired And Wireless LAN साखी
Show more

Popular Posts

Big Data MCQs(multiple choice questions) with answers - letsbug

Digital Marketing MCQ(Multiple Choice Questions) with Answers | part 1 | letsbug

Software Engineering MCQs questions with answers - letsbug