Tree in Javascript

A tree is non-linear and has a hierarchical data structure consisting of a collection of nodes such that each node of the tree stores a value and a list of references to other nodes (the “children”).

Tree Data Structure

Types of Trees:

Operations on tree data structure:

  • Insert: Insert an element in a tree/create a tree.
  • Search: Searches an element in a tree.
  • Tree Traversal: The tree traversal algorithm is used in order to visit a specific node in the tree to perform a specific operation on it.

Below is the implementation of Binary Search Tree in javascript:

Javascript
// Node class
class Node
{
    constructor(data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
// Binary Search tree class
class BinarySearchTree
{
    constructor()
    {
        // root of a binary search tree
        this.root = null;
    }

    // function to be implemented
    // helper method which creates a new node to
// be inserted and calls insertNode
insert(data)
{
    // Creating a node and initialising
    // with data
    var newNode = new Node(data);
                    
    // root is null then node will
    // be added to the tree and made root.
    if(this.root === null)
        this.root = newNode;
    else

        // find the correct position in the
        // tree and add the node
        this.insertNode(this.root, newNode);
}

// Method to insert a node in a tree
// it moves over the tree to find the location
// to insert a node with a given data
insertNode(node, newNode)
{
    // if the data is less than the node
    // data move left of the tree
    if(newNode.data < node.data)
    {
        // if left is null insert node here
        if(node.left === null)
            node.left = newNode;
        else

            // if left is not null recur until
            // null is found
            this.insertNode(node.left, newNode);
    }

    // if the data is more than the node
    // data move right of the tree
    else
    {
        // if right is null insert node here
        if(node.right === null)
            node.right = newNode;
        else

            // if right is not null recur until
            // null is found
            this.insertNode(node.right, newNode);
    }
}

    // helper method that calls the
// removeNode with a given data
remove(data)
{
    // root is re-initialized with
    // root of a modified tree.
    this.root = this.removeNode(this.root, data);
}

// Method to remove node with a
// given data
// it recur over the tree to find the
// data and removes it
removeNode(node, key)
{
        
    // if the root is null then tree is
    // empty
    if(node === null)
        return null;

    // if data to be delete is less than
    // roots data then move to left subtree
    else if(key < node.data)
    {
        node.left = this.removeNode(node.left, key);
        return node;
    }

    // if data to be delete is greater than
    // roots data then move to right subtree
    else if(key > node.data)
    {
        node.right = this.removeNode(node.right, key);
        return node;
    }

    // if data is similar to the root's data
    // then delete this node
    else
    {
        // deleting node with no children
        if(node.left === null && node.right === null)
        {
            node = null;
            return node;
        }

        // deleting node with one children
        if(node.left === null)
        {
            node = node.right;
            return node;
        }
        
        else if(node.right === null)
        {
            node = node.left;
            return node;
        }

        // Deleting node with two children
        // minimum node of the right subtree
        // is stored in aux
        var aux = this.findMinNode(node.right);
        node.data = aux.data;

        node.right = this.removeNode(node.right, aux.data);
        return node;
    }

}

                

    
    // finds the minimum node in tree
// searching starts from given node
findMinNode(node)
{
    // if left of a node is null
    // then it must be minimum node
    if(node.left === null)
        return node;
    else
        return this.findMinNode(node.left);
}

    
    // returns root of the tree
getRootNode()
{
    return this.root;
}


    // Performs inorder traversal of a tree
inorder(node)
{
    if(node !== null)
    {
        this.inorder(node.left);
        console.log(node.data);
        this.inorder(node.right);
    }
}

    // Performs preorder traversal of a tree
preorder(node)
{
    if(node !== null)
    {
        console.log(node.data);
        this.preorder(node.left);
        this.preorder(node.right);
    }
}

    
// Performs postorder traversal of a tree
postorder(node)
{
    if(node !== null)
    {
        this.postorder(node.left);
        this.postorder(node.right);
        console.log(node.data);
    }
}

    
    // search for a node with given data
search(node, data)
{
// if trees is empty return null
    if(node === null)
        return null;

    // if data is less than node's data
    // move left
    else if(data < node.data)
        return this.search(node.left, data);

    // if data is more than node's data
    // move right
    else if(data > node.data)
        return this.search(node.right, data);

    // if data is equal to the node data
    // return node
    else
        return node;
}

    
}
// create an object for the BinarySearchTree
var BST = new BinarySearchTree();

// Inserting nodes to the BinarySearchTree
BST.insert(15);
BST.insert(25);
BST.insert(10);
BST.insert(7);
BST.insert(22);
BST.insert(17);
BST.insert(13);
BST.insert(5);
BST.insert(9);
BST.insert(27);
                        
//        15
//      /   \
//     10    25
//     / \   / \
//    7   13 22 27
// / \  /
// 5 9 17

var root = BST.getRootNode();
            
// prints 5 7 9 10 13 15 17 22 25 27
console.log("Initial tree: ");
BST.inorder(root);
            
// Removing node with no children
BST.remove(5);

//        15
//      /   \
//     10    25
//     / \   / \
//    7   13 22 27
//   \  /
//   9 17
                        
var root = BST.getRootNode();
            
console.log("Tree after removing 5: ");
// prints 7 9 10 13 15 17 22 25 27
BST.inorder(root);
            
// Removing node with one child
BST.remove(7);
            
//         15
//         / \
//     10 25
//     / \ / \
//     9 13 22 27
//         /
//         17
            
            
var root = BST.getRootNode();

console.log("Tree after removing 7: ");
// prints 9 10 13 15 17 22 25 27
BST.inorder(root);
            
// Removing node with two children
BST.remove(15);
    
//         17
//         / \
//     10 25
//     / \ / \
//     9 13 22 27

var root = BST.getRootNode();
console.log("Inorder traversal: ");
// prints 9 10 13 17 22 25 27
BST.inorder(root);
            
console.log("Postorder traversal: ");
BST.postorder(root);

console.log("Preorder traversal: ");
BST.preorder(root);

Learn Data Structures with Javascript | DSA using JavaScript Tutorial

JavaScript (JS) is the most popular lightweight, interpreted compiled programming language, and might be your first preference for Client-side as well as Server-side developments. But have you thought about using Javascript for DSA? Learning Data Structures and Algorithms can be difficult when combined with Javascript. For this reason, we have brought to you this detailed DSA tutorial on how to get started with Data Structures with Javascript from scratch.

Data Structures with JavascriptData Structures with Javascript

Table of Content

  • What is Data Structure?
  • How to start learning Data Structures with Javascript?
  • Learn about Complexities
  • Learn Data Structures with JavaScript
  • Array in javascript
  • String in javascript
  • Linked List in Javascript
  • Stack in Javascript
  • Queue in Javascript
  • Tree in Javascript
  • Priority Queue in Javascript
  • Map in Javascript
  • Set in Javascript
  • Graph in Javascript

Similar Reads

What is Data Structure?

A data structure is defined as a particular way of storing and organizing data in our devices to use the data efficiently and effectively. The main idea behind using data structures is to minimize the time and space complexities. An efficient data structure takes minimum memory space and requires minimum time to execute the data....

How to start learning Data Structures with Javascript?

The first and foremost thing is dividing the total procedure into little pieces which need to be done sequentially....

1. Learn about Complexities

Here comes one of the interesting and important topics. The primary motive to use DSA is to solve a problem effectively and efficiently. How can you decide if a program written by you is efficient or not? This is measured by complexities. Complexity is of two types:...

2. Learn Data Structures

Here comes the most crucial and the most awaited stage of the roadmap for learning data structure and algorithm – the stage where you start learning about DSA. The topic of DSA consists of two parts:...

1. Array in javascript

An array is a collection of items of the same variable type stored that are stored at contiguous memory locations. It’s one of the most popular and simple data structures and is often used to implement other data structures. Each item in an array is indexed starting with 0....

2. String in javascript

JavaScript strings are used for storing and manipulating text. It can contain zero or more characters within quotes....

3.  Linked List in Javascript

A linked list is a linear data structure, Unlike arrays, linked list elements are not stored at a contiguous location. it is basically chains of nodes, each node contains information such as data and a pointer to the next node in the chain. In the linked list there is a head pointer, which points to the first element of the linked list, and if the list is empty then it simply points to null or nothing....

4. Stack in Javascript

Stack is a linear data structure in which insertion and deletion are done at one end this end is generally called the top. It works on the principle of Last In First Out (LIFO) or First in Last out (FILO). LIFO means the last element inserted inside the stack is removed first. FILO means, the last inserted element is available first and is the first one to be deleted....

5. Queue in Javascript

A Queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). It is similar to the ticket queue outside a cinema hall, where the first person entering the queue is the first person who gets the ticket....

6. Tree in Javascript

A tree is non-linear and has a hierarchical data structure consisting of a collection of nodes such that each node of the tree stores a value and a list of references to other nodes (the “children”)....

7. Priority Queue in Javascript

A priority queue is a type of queue that arranges elements based on their priority values. Elements with higher priority values are typically retrieved before elements with lower priority values....

8. Map in Javascript

Map is a collection of elements where each element is stored as a Key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, and value pair in the same order as inserted....

9.  Set in Javascript

A set is a collection of items that are unique i.e no element can be repeated. Set in ES6 are ordered: elements of the set can be iterated in the insertion order. Set can store any type of value whether primitive or objects...

10. Graph in Javascript

A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as, A Graph consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes....

3. Built-in Data Structures in JavaScript

Let’s see what inbuilt data structures JavaScript offers us:...

4. Practice Problems on Data Structures and Algorithms (DSA)

For practicing problems on individual data structures and algorithms, you can use the following links:...

Contact Us