DEV Community

Bvnkumar
Bvnkumar

Posted on • Updated on

Javascript Binary Tree data structure

Binary Tree:
A binary tree is a data structure consisting of a set of linked nodes that represent a hierarchical tree structure. Each node is linked to others via parent child relationship.
Any given node can have at most two children(left&right).

Internal structure of binary tree:

class Node {
    constructor(data, left = null, right = null) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
}

class BST {
    constructor() {
        this.root = null;
    }
    add(data) {
        const node = this.root;
        if (node == null) {
            this.root = new Node(data);
        } else {
            const searchTree = function(data) {
                if (data < node.data) {
                    if (node.left == null) {
                        node.left = new Node(data);
                        return;
                    } else if (node.left != null) {
                        return searchTree(node.left)
                    }
                } else if (data > node.data) {
                    if (node.right == null) {
                        node.right = new Node(data)
                        return;
                    } else if (node.right != null) {
                        return searchTree(node.right)
                    }
                } else {
                    return null;
                }
            }
            return searchTree(data)
        }
    }
    findMax() {
        let current = this.root;
        while (current.right != null) {
            current = current.right;
        }
        return current.data;
    }
    findMin() {
        let current = this.root;
        while (current.left != null) {
            current = current.left
        }
        return current.data;
    }
    find(data) {
        let current = this.root;
        while (current.data != null) {
            if (data < current.data) {
                current = current.left;
            } else {
                current = current.right;
            }
            if (current == null) {
                return null;
            }
        }
        return current;
    }
    isPresent(data) {
        let current = this.root;
        while (current) {
            if (data == current.data) {
                return true
            }
            if (data < current.data) {
                current = current.left;
            } else {
                current = current.right;
            }
        }
        return false;
    }
}

const bst = new BST();
bst.add(1);
bst.add(2);
bst.add(3);
console.log(bst.findMin());
console.log(bst.findMax());
console.log(bst.find(1));
console.log(bst.isPresent(1));
Enter fullscreen mode Exit fullscreen mode

Any comments or suggestions are welcome.

Top comments (0)