Skip to content

bst in js #8

Open
Open
@prabaprakash

Description

@prabaprakash
let node = (data) => ({
  left: null,
  right: null,
  data: data
})
let bst = {
  root: null,
  insert: (root = bst.root, data) => {
    if (root === null) {
      bst.root = node(data);
    } else {
      if (data < root.data) {
        root.left = root.left === null ? node(data) : bst.insert(root.left, data);
      }
      else {
        root.right = root.right === null ? node(data) : bst.insert(root.right, data);
      }
    }
    return root;
  },
  postorder: (root) => {
    if (root !== null) {
      bst.postorder(root.left);
      bst.postorder(root.right);
      console.log(root.data);
    }
  },
  inorder: (root) => {
    if (root !== null) {
      bst.inorder(root.left);
      console.log(root.data);
      bst.inorder(root.right);
    }
  },
  remove: (root, data) => {
    if (root === null) return null;
    else if (data > root.data) {
      root.right = bst.remove(root.right, data);
      return root;
    }
    else if (data < root.data) {
      root.left = bst.remove(root.left, data);
      return root;
    }
    else {

      if (root.left == null && root.right === null) {
        root = null;
        return root;
      }
      if (root.left === null) {
        root = root.right;
        return root;
      }
      else if (root.right === null) {
        root = root.left;
        return root;
      }

      // Deleting node with two children 
      // minumum node of the rigt subtree 
      // is stored in aux 
      let aux = bst.findMinNode(root.right);
      root.data = aux.data;

      root.right = bst.remove(root.right, aux.data);
      return root;
    }
  },
  findMinNode: (root) =>{
     if(root.left === null) return root;
     root = bst.findMinNode(root.left);
     return root;
  }
}


bst.insert(bst.root, 15);
bst.insert(bst.root, 25);
bst.insert(bst.root, 10);
bst.insert(bst.root, 7);
bst.insert(bst.root, 22);
bst.insert(bst.root, 17);
bst.insert(bst.root, 13);
bst.insert(bst.root, 5);
bst.insert(bst.root, 9);
bst.insert(bst.root, 27);

console.log(JSON.stringify(bst.root));

bst.remove(bst.root, 5);


bst.remove(bst.root, 7);
// bst.inorder(bst.root);

bst.remove(bst.root, 15);
bst.inorder(bst.root);

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy