Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node {
- constructor(data) {
- this.data = data;
- this.left = null;
- this.right = null;
- this.parent = null;
- }
- }
- class BST {
- constructor(data) {
- this._root = new Node(data);
- }
- recurseAdd(data, currNode=this._root) {
- let newNode = new Node(data);
- if (data <= currNode.data) {
- // leftNode - empty
- if(!currNode.left) {
- currNode.left = newNode;
- newNode.parent = currNode;
- // leftNode - exists
- } else {
- currNode = currNode.left;
- this.recurseAdd(data, currNode);
- }
- } else {
- // leftNode - empty
- if(!currNode.right) {
- newNode.parent = currNode;
- currNode.right = newNode;
- // leftNode - exists
- } else {
- currNode = currNode.right;
- this.recurseAdd(data, currNode);
- }
- }
- }
- add(data, currNode=this._root) {
- let newNode = new Node(data);
- while(currNode) {
- if (data <=currNode.data) {
- // leftNode - empty
- if (!currNode.left) {
- newNode.parent = currNode;
- currNode.left = newNode;
- break;
- // leftNode - exists
- } else {
- currNode = currNode.left;
- }
- } else {
- // leftNode - empty
- if (!currNode.right) {
- newNode.parent = currNode;
- currNode.right = newNode;
- break;
- // leftNode - exists
- } else {
- currNode = currNode.right;
- }
- } // end of outer-most else
- } // end of while
- } // end of iterative ADD
- /* PRINT OUT VALUES - BFS Traversal */
- BFS(currNode=this._root, queue=[], results=[]) {
- if (currNode === null) {return;}
- // push rootNode to stack
- queue.push(currNode);
- let len = queue.length;
- while (queue.length !== 0) {
- // check if left child exists
- if (currNode.left) {
- queue.push(currNode.left);
- }
- // check if right child exists
- if (currNode.right) {
- queue.push(currNode.right);
- }
- // remove 'first element' in [queue]
- let node = queue.shift();
- let nodeVal = node.data;
- //console.log(`nodeVal: ${nodeVal}`);
- results.push(nodeVal);
- currNode = queue[0];
- } // end of while-loop
- return results;
- } // end of BFS
- }
- let hi = new BST('f');
- hi.add('d');
- hi.add('k');
- hi.add('b');
- hi.add('e');
- hi.add('g');
- hi.add('l');
- hi.add('a');
- hi.add('c');
- hi.add('h');
- hi.add('j');
- /* console.log(hi._root); */
- // BFS
- let result = hi.BFS();
- console.log(`Printed Values in BFS: [${result}]`);
Add Comment
Please, Sign In to add comment