Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bst in js #8

Open
prabaprakash opened this issue Aug 26, 2020 · 1 comment
Open

bst in js #8

prabaprakash opened this issue Aug 26, 2020 · 1 comment

Comments

@prabaprakash
Copy link
Owner

prabaprakash commented Aug 26, 2020

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);
@prabaprakash
Copy link
Owner Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant