JSFiddle - React, Tailwind, and code Playground

by CommandLineDesign

JavaScript

function BinarySearchTree(){
	var _root = null;
	Object.defineProperty(this, '_root'){
  	get: function(){
			return _root;
		}
  };
  Object.defineProperty(this, 'contents'){
  	
  };
  Object.defineProperty(this, 'size'){
  	
  };
}

BinarySearchTree.prototype = {
	contains: function(value){
  	var found = false,
    	current = this._root;
    while(!found && current){
    	//if less than current node, go left.
    	if(value < current.value){
      	current = current.left;
      //if greater than current node, go right.
      } else if (value < current.value){
      	current = current.right;
      //values are equal, found it!
      } else {
      	found = true;
      }
      //proceed when found
      return found;
    }
  },
  add: function(value){
  	//create a new node instance
    var node = {
    	value: value,
      left: null,
      right: null
    },
    //Used to traverse tree structure
    current;
    //Param root if tree is empty.
    if(this._root === null){
    	this._root = node;
    } else {
    
      current = this._root;

      while(true){
				//if the new value is less than this node's value, go left
        if(value < current.value){
        	//if there's no left, then the new node belongs there
          if(current.left === null){
          	current.left = node;
            break;
          } else {
          	current = current.left;
          }
        } else if (value > current.value){
        	//if there's no right, then the new node belongs there
          if(current.right === null){
          	current.right = node;
            break;
          } else {
          	current = current.right;
          }
        //if the new value is equal to the current one, just ignore it
        } else {
        	break;
        }
      }	
    }
  },
  traverse: function(process){
  	//helper function
    function inOrder(node){
    	if (node){
      	//traverse the left subree
        if(node.left !== null){
        	inOrder(node.left);
        }
    ...