int main()
{
    BinarySearchTree bTree;
    Node* bTreeRoot = nullptr;
    bTree.insertNode(bTreeRoot,12);
    bTree.insertNode(bTreeRoot,7);
    bTree.insertNode(bTreeRoot,22);
    bTree.insertNode(bTreeRoot,4);
    bTree.insertNode(bTreeRoot,9);
    bTree.insertNode(bTreeRoot,15);
    bTree.insertNode(bTreeRoot,29);
    bTree.insertNode(bTreeRoot,1);
    bTree.insertNode(bTreeRoot,5);
    bTree.insertNode(bTreeRoot,8);
    bTree.insertNode(bTreeRoot,11);
    bTree.insertNode(bTreeRoot,13);
    bTree.insertNode(bTreeRoot,18);
    bTree.insertNode(bTreeRoot,24);
    bTree.insertNode(bTreeRoot,31);
    //bTree.inorder(bTreeRoot);
    bTree.setRoot(bTreeRoot);
    cout<< "The ancestor is " << bTree.findLCA(13,29)<<endl;
    cout<< "The distance between nodes is " << bTree.computeDistance(13,29)<<endl;
    return 0;
}
int
main()
{

	clock_t t;
    int i;



    BinarySearchTree<string> bt
        (
        new BinaryNode<string>("Lee",
                new BinaryNode<string>("Christie",
                        new BinaryNode<string>("Russ",NULL,NULL),
                        new BinaryNode<string>("Andrew",NULL,NULL)
                        ),
                new BinaryNode<string>("Tom",
                        new BinaryNode<string>("Conner",NULL,NULL),
                        new BinaryNode<string>("Ellie",NULL,NULL)
                        )
                ),
        ""
        );

    BinarySearchTree<string> bt2
        (
        new BinaryNode<string>("Russ",
                new BinaryNode<string>("Christie",
                        new BinaryNode<string>("Andrew",NULL,NULL),
                        new BinaryNode<string>("Lee",
                            new BinaryNode<string>("Conner",NULL,
                                new BinaryNode<string>("Ellie",NULL,NULL)),
                            NULL)
                        ),
                new BinaryNode<string>("Tom",NULL,NULL)
                ),
        ""
        );

    BinarySearchTree<string> bt3
        (
        new BinaryNode<string>("A",
            new BinaryNode<string>("B",
                new BinaryNode<string>("D",NULL,NULL),
                new BinaryNode<string>("E",NULL,NULL)
                ),
            new BinaryNode<string>("C",
                new BinaryNode<string>("F",NULL,NULL),
                NULL
            )
        ),
    ""
    );

    BinarySearchTree<string> bt4
        (
        new BinaryNode<string>("D",
            new BinaryNode<string>("B",
                new BinaryNode<string>("A",NULL,NULL),
                new BinaryNode<string>("C",NULL,NULL)
                ),
            new BinaryNode<string>("F",
                new BinaryNode<string>("E",NULL,NULL),
                NULL
            )
        ),
    ""
    );

    BinarySearchTree<string> bt5
        (
        new BinaryNode<string>("D",
            new BinaryNode<string>("G",
                new BinaryNode<string>("A",NULL,NULL),
                new BinaryNode<string>("B",NULL,NULL)
                ),
            new BinaryNode<string>("F",
                new BinaryNode<string>("E",NULL,NULL),
                NULL
            )
        ),
    ""
    );

    BinarySearchTree<string> bt6
        (
        new BinaryNode<string>("D",
            new BinaryNode<string>("B",
                new BinaryNode<string>("A",NULL,NULL),
                new BinaryNode<string>("G",NULL,NULL)
                ),
            new BinaryNode<string>("F",
                new BinaryNode<string>("E",NULL,NULL),
                NULL
            )
        ),
    ""
    );

    BinarySearchTree<string> bt7
        (
        new BinaryNode<string>("D",
            new BinaryNode<string>("C",
                new BinaryNode<string>("A",NULL,NULL),
                new BinaryNode<string>("B",NULL,NULL)
                ),
            new BinaryNode<string>("F",
                new BinaryNode<string>("E",NULL,NULL),
                NULL
            )
        ),
    ""
    );


    cout << isBST(bt);
    cout << '\n';
    cout << '\n';

    bt.printTree_inorder();
    cout << '\n';
    bt2.printTree_inorder();
    cout << '\n';
    bt3.printTree_inorder();
    cout << '\n';

    bt4.printTree_inorder();
    cout << '\n';
    bt5.printTree_inorder();
    cout << '\n';
    bt6.printTree_inorder();
    cout << '\n';
    bt7.printTree_inorder();
    cout << '\n';


}
Exemplo n.º 3
0
void test_remove() {
	BinarySearchTree * tree = new BinarySearchTree;
	//remove empty tree
	cout << tree->remove(2);
	test_insert(tree);
	tree->print_tree();
	tree->remove(10);
	tree->print_tree();


	//remove 2 children
	tree->remove(8);
	tree->print_tree();
	//remove 1 child
	tree->remove(2);
	tree->print_tree();
	//remove no children
	tree->remove(3);
	tree->print_tree();
	//remove no parent
	tree->remove(5);
	tree->print_tree();
	tree->remove(5);
	tree->print_tree();
	//remove doesn't exist
	tree->remove(8);
	tree->print_tree();
	//remove only right child
	tree->insert(10);
	tree->insert(11);
	tree->insert(12);
	tree->print_tree();
	tree->remove(10);
	tree->print_tree();

}
Exemplo n.º 4
0
BinarySearchTree<BSTNode1<int>, int> treeMaker(int i){
	BinarySearchTree<BSTNode1<int>, int> tree;
	if(i == 1){
		tree.add(10);
		tree.add(5);
		tree.add(15);
		tree.add(3);
		tree.add(0);
		tree.add(2);
	}else{
		tree.add(20);
		tree.add(10);
		tree.add(30);
		tree.add(5);
		tree.add(15);
		tree.add(25);
		tree.add(35);
	}
	return tree;
}
Exemplo n.º 5
0
int main(int argc, char **argv)
{
    BinarySearchTree bst;
    bst.insert(12);
    bst.insert(34);
    bst.insert(9);
    bst.insert(54);
    bst.insert(134);
    bst.insert(4);
    bst.insert(19);
    bst.insert(5);


    bst.printTree();

    cout << "-------------------------" << endl;
    cout<< bst.findMin(bst.thisone())->element << endl;
    cout<< bst.findMax(bst.thisone())->element << endl;

	return 0;
}
bool BinarySearchTree::remove(BinarySearchTree::DataType val)
{
	if (!exists(val))
		return false;
	
	if (size_ == 1)
	{
		root_ = NULL;
		size_--;
		return true; 
	}
	
	Node* index = root_;
	Node* parent = root_;
	
	while (index->val != val) 
	{
		parent = index; 
		if (val < index->val)
		{
			index = index->left;
		}
		else
		{
			index = index->right;
		}
	}
	
	bool left = false;
	if (parent->val > index->val)
		left = true;
	
	if (index->right == NULL && index->left == NULL)
	{
		if (left)
			parent->left = NULL;
		else 
			parent->right = NULL;
		delete index; 
	}
	
	else if (index->right == NULL && index->left != NULL)
	{
		if (left)
			parent->left = index->left; 	
		else 
			parent->right = index->left;
		//delete index; 
	}
	
	else if (index->right != NULL && index->left == NULL)
	{
		if (left)
			parent->left = index->right; 	
		else 
			parent->right = index->right;
		//delete index; 
	}
	
	else 
	{
		BinarySearchTree* preTree = new BinarySearchTree(); 
		BinarySearchTree* susTree = new BinarySearchTree(); 
		preTree->root_ = index->left;
		preTree->size_ = preTree->depth()+1;
		susTree->root_ = index->right;
		susTree->size_ = susTree->depth()+1;
		
		int pred = preTree->max();
		int succ = susTree->min();
		
		if ((val-pred) < (succ-val))
		{
			index->val = pred; 
			preTree->remove(pred);
		}
		else
		{
			index->val = succ;
			susTree->remove(succ);	
		}		
	}
	size_--;
	updateNodeBalance(root_); 
	return true; 
}
Exemplo n.º 7
0
/*
Function Name: INQUIRY
Purpose: to begin a search for a suspect.
Allows the use of Tip, Check and Print
*/
string INQUIRY(BinarySearchTree tree)
{
    //Define loop and inquiry vars
    string sessionName, command, exitCommand;
    bool inquiryEnd = false;
    int suspectsLeft;
    //Initialize exitCommand to a specific value to
      //be read by the main function in case of
      //improper session name.
    exitCommand = "IMPROPER";
    //Make new tree and copy so I'm not constantly
      //referencing the tree.
    BinarySearchTree inquiryTree;
    inquiryTree = tree;
    //Begin prompting user
    cout << "Enter a name for this inquiry:" << endl;
    getline (cin, sessionName);
    //If sessionName is of appropriate length
    if(sessionName.length() > 0 & sessionName.length() < 31) {
      while (inquiryEnd == false){
        cout << "Now doing inquiry: " << sessionName;
        //line split because of character limit
        cout << ". You can use CHECK, PRINT or TIP." << endl;
        cout << "(ADD, INQUIRY or QUIT will break ";
        cout << "you out of the inquiry.)" << endl;
        cout << endl;
        getline (cin, command);
        upCase(command);
        if (command == "TIP") {
          TIP(inquiryTree);
          //Always reset suspectsLeft to 0 before calling
            //countSuspects because it is an incrementer.
          suspectsLeft = 0;
          inquiryTree.countSuspects(countRemainingSuspects, 
                   suspectsLeft);
          if(suspectsLeft == 1) {
            cout << "ALERT! That leaves only one" << endl;
            cout << "suspect in the " << sessionName;
            cout << " inquiry: ";
            //Since there's only one suspect, just call
              //the traverse function used in the PRINT
              //function.
            inquiryTree.inorderTraverse(printVisit);
          } else if (suspectsLeft == 0) {
            cout << "ALERT! That means there are no suspects" << endl;
            cout << "left in the " << sessionName;
            cout << " inquiry." << endl;
          }
        } else if (command == "CHECK"){
          CHECK(inquiryTree);
        } else if (command == "PRINT"){
          PRINT(inquiryTree);
        } else if (command == "ADD" | command == "INQUIRY"
                                  | command == "QUIT") {
            exitCommand = command;
            inquiryEnd = true;
            //destroy the inquiry tree to save memory
            inquiryTree.~BinarySearchTree();
            cout << endl;
            cout << "Ending inquiry: " << sessionName << endl;
            cout << endl;
        }
      }
    }
    return exitCommand;
}
Exemplo n.º 8
0
void postorder(const BinarySearchTree<ItemType>& BinSearchTree)
{
	cout << endl << "PostOrder:" << endl;
	BinSearchTree.postorderTraverse(display);
}
int main(int argc, char *argv[]) {
     BinarySearchTree<int> *bst = new BinarySearchTree<int>();
     int a[] = {4,2,6,1,3,5,7,100,400};
     //int a[] = {4,2,6,1,3,5,7};//,100,400};

     for (int i: a) {
          bst->insert(&(bst->root), i);
     }
     cout << "Pre Order traversal" << endl;
     bst->preOrderTraversal(bst->root);
     cout << endl;
     cout << "In Order traversal" << endl;
     bst->inOrderTraversal(bst->root);
     cout << endl;
     cout << "Post Order traversal" << endl;
     bst->postOrderTraversal(bst->root);
     cout << endl;
     cout << "Tree size: " << bst->size(bst->root) << endl;
     //bst->mirror(&bst->root);
     //cout << "Mirrored Tree" << endl;
     //bst->inOrderTraversal(bst->root);
     //cout << endl;

     cout << "Breadth first search" << endl;
     bst->bfs(bst->root);
     cout << endl;
     cout << "Max Tree Depth: " << bst->maxDepth(bst->root) << endl;

     Node<int> *clonedTree = bst->cloneTree(bst->root);
     cout << "In Order traversal of the cloned tree" << endl;
     bst->inOrderTraversal(clonedTree);
     cout << endl;
     cout << "Cloned Tree max depth: " << bst->maxDepth(clonedTree) << endl;
     cout << "Has path: " << ((bst->hasPathSum(clonedTree, 8) == true) ? "True" : "False") << endl;
     return 0;
}
Exemplo n.º 10
0
#include "../tests/catch.hpp"
#include "../include/BinarySearchTree.h"

SCENARIO ("Size must decrease"){
  GIVEN ("Tree and its size"){
    BinarySearchTree<int> tree{11, 12, 15, 9, 10, 14, 17, 13};
    auto size = tree.ReturnSize();
    tree.Remove(13);
    THEN ("Size decrease"){
      REQUIRE(tree.ReturnSize() == size - 1);
    }
  }
}

SCENARIO ("Changing the tree")
{
  GIVEN ("Two trees")
  {
    WHEN ("Remove root")
    {
      BinarySearchTree<int> tree1{11};
      BinarySearchTree<int> tree2;
      tree1.Remove(11);
      THEN ("Tree must be equal"){
         REQUIRE(tree1 == tree2);
      }
    }
    WHEN ("Root without offsprings")
    {
      BinarySearchTree<int> tree1{11, 12, 9};
      BinarySearchTree<int> tree2{11, 9};
Exemplo n.º 11
0
void inorder(const BinarySearchTree<ItemType>& BinSearchTree)
{
	cout << endl << "Inorder:" << endl;
	BinSearchTree.inorderTraverse(display);
}
Exemplo n.º 12
0
#include "catch.hpp"
#include "binary.hpp"

SCENARIO("Testing Integer Binary Search Tree") {

  SECTION("Testing Building Methods") {

    GIVEN("an empty tree") {
      BinarySearchTree<int> bst;

      WHEN("we have not yet inserted some items") {

	THEN("the tree is still empty") {
	  REQUIRE(bst.is_empty());
	}
      }

      WHEN("we insert the first item (1)") {
	bst.insert(1);

	THEN("the tree is not empty anymore") {
	  REQUIRE_FALSE(bst.is_empty());
	}

	AND_THEN("we can get the root of the tree") {
	  BinaryNode<int> *root_ptr = bst.get_root();
	  CHECK(root_ptr);
	}

	AND_WHEN("we insert another smaller item (0)") {
	  bst.insert(0);
Exemplo n.º 13
0
// Main
int main(int argc, char **argv)
{
	// Build sample test data using 16 integer array
	int NodeValueTestData[16] = { 50,76,21,4,32,64,15,52,14,100,83,2,3,70,87,80 };

	// Binary Search Tree object
	BinarySearchTree testTree; 

	// Test PrintInOrder Function
	cout << "Printing tree in-order\nBefore adding numbers\n";
	testTree.PrintInOrder();

	
	// Iterate and add all 16 integers to the tree following
	// properties of the BST, then print out the tree
	for(int i = 0; i < 16; i++ )
	{
		testTree.AddLeafNode(NodeValueTestData[i]);
	}
	
	cout << "Printing tree in-order\nAfter adding numbers\n";

	testTree.PrintInOrder();
	
	cout << endl;

	//testTree.PrintChildrenOfCurrentNode(testTree.ReturnRootNodeValue());

	cout << endl;
	
	// Iterate and print all children of the root node
	// for(int i = 0; i < 16; i++ )
	// {
	// 	testTree.PrintChildrenOfCurrentNode(NodeValueTestData[i]);
	// 	cout << endl;
	// }

	
	cout << "Smallest value in tree is " << testTree.FindSmallestNodeValueInTree() << endl;
	cout << endl;
	cout << endl;
	cout << endl;
	cout << endl;
	cout << "\n--------------------------------------------------------\n\n" << endl;
	int input;
	cout << "Enter a key (node value) for deletion. Enter -1 to quit" << endl;
	while(input != -1)
	{
		cout << "Delete Node: ";
		cin >> input;
		{
			if(input != -1)
			{
				cout << endl;
				testTree.RemoveNode(input);
				testTree.PrintInOrder();
				cout << endl;
			}	
		}
	}

	return 0;
}
Exemplo n.º 14
0
int main()
{
   //the unsorted ListArray of cds
   ListArray<CD>* cds = CD::readCDs("cds.txt");
   int numItems = cds->size();
   cout << numItems << endl;
   cout << endl;

   //test the binary search tree
   //insert all of the cds
   ListArrayIterator<CD>* iter = cds->iterator();
   BinarySearchTree<CD>* bst = new BinarySearchTree<CD>(&CD::compare_items, &CD::compare_keys);
   while(iter->hasNext())
   {
      CD* cd = iter->next();
      bst->insert(cd);
   }
   delete iter;

   BinaryTreeIterator<CD>* bst_iter = bst->iterator();
   bst_iter->setInorder();  //takes a snapshot of the data
   while(bst_iter->hasNext())
   {
      CD* cd = bst_iter->next();
      //cd->displayCD();
   }
   delete bst_iter;

   int height = bst->getHeight();
   bool balance = bst->isBalanced();

   if(balance == true)
   {
       cout << "\nThe height is " << height << " and it is balanced.\n";
   }
   else
   {
       cout << "\nThe height is " << height << " and it is not balanced.\n";
   }

   //create a minimum height binary search tree
   BinarySearchTree<CD>* min_bst = bst->minimize();
   bst_iter = min_bst->iterator();

   //make sure that an inorder traversal gives sorted order
   bst_iter->setInorder();  //takes a snapshot of the data
   while(bst_iter->hasNext())
   {
      CD* cd = bst_iter->next();
      //cd->displayCD();
   }
   delete bst_iter;

   height = min_bst->getHeight();
   balance = min_bst->isBalanced();

   if(balance == true)
   {
       cout << "\nThe minimum height is " << height << " and it is balanced.\n";
   }
   else
   {
       cout << "\nThe minimum height is " << height << " and it is not balanced.\n";
   }

   //create a complete binary search tree
   BinarySearchTree<CD>* complete_bst = bst->minimizeComplete();
   delete bst;

   //make sure that an inorder traversal gives sorted order
   bst_iter = complete_bst->iterator();										
   bst_iter->setInorder(); //takes a snapshot of the data
   while(bst_iter->hasNext())
   {
      CD* cd = bst_iter->next();
      //cd->displayCD();
   }
   delete bst_iter;

   height = complete_bst->getHeight();
   balance = complete_bst->isBalanced();

   if(balance == true)
   {
       cout << "\nThe minimum height is " << height << " and it is balanced.\n";
   }
   else
   {
       cout << "\nThe minimum height is " << height << " and it is not balanced.\n";
   }

   delete complete_bst;

   deleteCDs(cds);
   delete cds;
   return 0;
}
Exemplo n.º 15
0
int main(int argc, char *argv[]) {
  BinarySearchTree<int> BST;
  assert(BST.insert(4) == true);
  assert(BST.insert(5) == true);
  assert(BST.insert(2) == true);
  assert(BST.insert(3) == true);
  assert(BST.insert(1) == true);
  assert(BST.erase(0) == false);
  assert(BST.erase(2) == true);
  assert(BST.erase(2) == false);
  assert(BST.insert(4) == false);
  // should output 4
  assert(BST.getRootVal() == 4);
  cout << BST.getRootVal() << endl;
  assert(BST.erase(4) == true);
  // should output 5
  assert(BST.getRootVal() == 5);
  cout << BST.getRootVal() << endl;
  assert(BST.erase(5) == true);
  // should output 3
  assert(BST.getRootVal() == 3);
  cout << BST.getRootVal() << endl;
  return 0;
}
Exemplo n.º 16
0
int main(int argc, char** argv) {
    BinarySearchTree<int, int> intTree;
    
    intTree.add(40);
    intTree.add(5);
    intTree.add(10);
    intTree.add(30);
    intTree.add(20);
    intTree.add(35);
    intTree.add(25);
    intTree.add(15);

    cout << intTree.getHeight() << endl;
    cout << intTree.getNumberOfNodes() << endl;

    int item;

    cout << "Inorder\n";
    intTree.inorderTraverse(print);

    cout << "Get entry for 5 " << intTree.getEntry(5) << endl;
    cout << "Get entry for 25 " << intTree.getEntry(25) << endl;
    try {
        cout << "Get entry for 65 " << intTree.getEntry(65) << endl;
    } catch(NotFoundException e) {
        cout << "Error " << e.what() << endl;
    }

    cout << "Does it contain 5 " << intTree.contains(5) << endl;
    cout << "Does it contain 25 " << intTree.contains(25) << endl;
    cout << "Does it contain 65 " << intTree.contains(65) << endl;

    try {
        intTree.remove(40);
    } catch(NotFoundException e) {
        cout << "Error " << e.what() << endl;
    }
    intTree.inorderTraverse(print);
    cout << endl;
    intTree.remove(30);
    intTree.inorderTraverse(print);
    cout << endl;
    intTree.remove(5);
    intTree.inorderTraverse(print);
    cout << endl;
    intTree.remove(15);
    intTree.inorderTraverse(print);
    cout << endl;
    cout << intTree.getHeight() << endl;
    cout << intTree.getNumberOfNodes() << endl;
}
Exemplo n.º 17
0
//-----------------------------END of BinarySearchTree Class---------------------------------//
// START of Main-----
int main(int argc, const char * argv[]) {
    
    BSTNode n1 (137);
    BSTNode n2 (122);
    //    n1.setLeft (&n2);
    BSTNode n3 (116);
    //    n2.setLeft (&n3);
    BSTNode n4 (120);
    //    n3.setRight (&n4);
    //    n1.print ();
    //    cout << endl;
    //    n2.print ();
    //    cout << endl;
    //    n3.print ();
    //    cout << endl;
    //    n4.print ();
    //    cout << endl;
    
    int arr[1000];
    arr[1000] = *storeRandomNumbersInArray(arr);
    
    //    int numberToSeed = 0;
    //    cout<<"Enter random number to seed:\n";
    //    cin>>numberToSeed;
    
    BinarySearchTree tree;
    
    //add array of random numbers to Binary Search Tree.
    for (int i = 0; i<1000; i++) {
        tree.add (arr[i]);
    }
    
    
    cout<<"i    BFS    DFS\n";
    for (int i = 1; i <= 10; i++) {
        int travCount = tree.breadthFirstTraversal (i*100);
        cout<<i<<"    "<<travCount<<endl;
    }
    
    //    cout<<"Traversal Count:"<<tree.breadthFirstTraversal (759)<<endl;
    
    return 0;
    
    
    /*
     //Working on UnorderedLinkedList & Stack and Queues.
     BSTNode *ptr = &n1;
     
     UnorderedLinkedList l1;
     l1.addAtHead (&n1);
     l1.print ();
     l1.addAtTail(&n2);
     l1.print ();
     l1.addAtTail(&n3);
     l1.print ();
     l1.addAtHead(&n4);
     l1.print ();
     cout<<endl;
     l1.removeFromHead(ptr);
     l1.print ();
     
     */
    
    return 0;
}//end main
Exemplo n.º 18
0
void basic_test()
{
    BinarySearchTree<int> tree;
    for (int i = 0; i < 15; i += 3) tree.insert(i);

    assert(tree.size() == 5);
    assert(tree.search(3));
    assert(tree.search(12));
    assert(!tree.search(10));
    assert(!tree.erase(8));
    assert(tree.search(9));
    assert(tree.erase(9));
    assert(!tree.erase(9));
    assert(tree.size() == 4);
    assert(!tree.insert(3));
    assert(tree.insert(13));
    assert(tree.size() == 5);
    assert(tree.erase(13));
    assert(tree.erase(12));
    assert(tree.erase(6));
    assert(tree.erase(3));
    assert(tree.erase(0));
    assert(tree.empty());
}
Exemplo n.º 19
0
#include "catch.hpp"
#include "../DataStructs/BinarySearchTree.h"
using namespace std;
using namespace dw;

BinarySearchTree<int> emptyTree;
BinarySearchTree<int> intTree;
BinarySearchTree<string> stringTree;

TEST_CASE("Add item test.", "[BST]")
{
   bool isAdded = intTree.add(20);
   REQUIRE(isAdded == true);
   isAdded = intTree.add(30);
   REQUIRE(isAdded == true);
   isAdded = intTree.add(40);
   REQUIRE(isAdded == true);
   isAdded = intTree.add(15);
   REQUIRE(isAdded == true);
   isAdded = intTree.add(35);
   REQUIRE(isAdded == true);
   isAdded = intTree.add(25);
   REQUIRE(isAdded == true);
   isAdded = intTree.add(5);
   REQUIRE(isAdded == true);
   isAdded = intTree.add(2);
   REQUIRE(isAdded == true);
   isAdded = intTree.add(7);
   REQUIRE(isAdded == true);
   isAdded = intTree.add(17);
   REQUIRE(isAdded == true);
int main(){

	cout << "HOMEWORK EXAMPLE:" << endl;
	BinarySearchTree<int, int> bst;
	bst.insert(make_pair(10,0));
	bst.insert(make_pair(4,0));
	bst.insert(make_pair(20,0));
	bst.insert(make_pair(2,0));
	bst.insert(make_pair(8,0));
	bst.insert(make_pair(14,0));
	bst.insert(make_pair(24,0));
	bst.insert(make_pair(6,0));
	bst.insert(make_pair(12,0));
	bst.insert(make_pair(18,0));
	bst.insert(make_pair(22,0));
	bst.insert(make_pair(16,0));

	bst.print();

	bst.insert(make_pair(15,0));
	bst.print();

	bst.insert(make_pair(17,0));
	bst.print();

	bst.insert(make_pair(11,0));
	bst.print();

	bst.remove(20);
	bst.print();

	bst.remove(16);
	bst.print();

	bst.remove(4);
	bst.print();
	
	cout << "TESTING ITERATOR:" << endl;
	for(BinarySearchTree<int, int>::iterator it = bst.begin(); it != bst.end(); ++it)
	{
		cout << it->first << ", ";
	}
	cout << endl << endl;

	cout << "TESTING INCREASING INSERT:" << endl;
	BinarySearchTree<int, int> bst2;
	for(int i=0; i<5; i++)
	{
		bst2.insert(make_pair(i, 0));
	}
	bst2.print();

	cout << "TESTING DECREASING INSERT:" << endl;
	for(int i=9; i>=5; i--)
	{
		bst2.insert(make_pair(i, 0));
	}
	bst2.print();



	cout << "TESTING INCREASING DELETION:" << endl;
	for(int i=0; i<10; i=i+2)
	{
		bst2.remove(i);
	}
	bst2.print();

	cout << "TESTING WEIRD DELETIONS:" << endl;
	bst2.remove(7);
	bst2.remove(3);
	bst2.remove(5);

	bst2.print();

	return 0;
}
Exemplo n.º 21
0
int main() {
	 BinarySearchTree<BSTNode1<int>, int>* tree = new BinarySearchTree<BSTNode1<int>, int>();
  tree->add(10);
  tree->add(12);
  tree->add(3);
  tree->add(9);
  tree->add(7);
  tree->add(2);
  tree->add(43);
  tree->add(4);
  tree->add(29);
  tree->add(37);

  testPart1(tree);
  cout << endl;

  BinarySearchTree<BSTNode1<int>, int>* tree2 = new BinarySearchTree<BSTNode1<int>, int>();
  tree2->add(5);
  tree2->add(4);
  tree2->add(6);
  tree2->add(10);
  tree2->add(11);

  testPart2(tree2);
  cout << endl;

  BinarySearchTree<BSTNode1<int>, int>* tree3 = new BinarySearchTree<BSTNode1<int>, int>();
  tree3->add(5);
  tree3->add(4);
  tree3->add(6);

  testPart2(tree2);
  cout << endl;

  BinarySearchTree<BSTNode1<int>, int>* tree4 = new BinarySearchTree<BSTNode1<int>, int>();
  tree4->add(5);
  tree4->add(12);
  tree4->add(3);
  tree4->add(4);
  tree4->add(9);
  tree4->add(7);
  tree4->add(2);
  tree4->add(13);

  testPart3(tree4);
  cout << endl;

  BinarySearchTree<BSTNode1<int>, int>* tree5 = new BinarySearchTree<BSTNode1<int>, int>();
  tree5->add(10);
  tree5->add(11);
  tree5->add(13);
  tree5->add(9);
  tree5->add(6);
  tree5->add(2);
  tree5->add(3);

  testPart4(tree5);

  delete tree;
  delete tree2;
  delete tree3;
  delete tree5;
  delete tree4;

  return 0;
}
Exemplo n.º 22
0
int main()
{  
   int input;
   BinarySearchTree bin;
   string binarycode;
   int size = 0;


   cout << "Please input a set of distinct nonnegative numbers for a Tree (Enter -1 when you are finished):" << endl;
   while (cin >> input)
		if (input == -1)
			break;
		else
		bin.insert(input);

   int largest = bin.largest();
   cout << "\nThe maximum of the entries is: " << largest;
   int smallest = bin.smallest();
   cout << "\nThe minimum of the entries is: " << smallest;
   
   size = bin.size();
   cout << "\nThe size of the List is: " << size;
   
   cout << endl;

   input = 1;
   while (input != -1)
   {
	   cout << "Select a value for insertion (Enter -1 when finished): ";
	   cin >> input;
	   if (input != -1)
		   bin.insert(input);
	   else
		   break;
   }

   largest = bin.largest();
   cout << "\nThe maximum of the entries is: " << largest;
   smallest = bin.smallest();
   cout << "\nThe minimum of the entries is: " << smallest;
   
   size = bin.size();
   cout << "\nThe size of the List is: " << size << endl;
   

   binarycode = bin.BinaryCode(1);
   cout << "The binary code for 1 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(2);
   cout << "The binary code for 2 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(3);
   cout << "The binary code for 3 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(4);
   cout << "The binary code for 4 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(5);
   cout << "The binary code for 5 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(6);
   cout << "The binary code for 6 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(7);
   cout << "The binary code for 7 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(8);
   cout << "The binary code for 8 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(9);
   cout << "The binary code for 9 is: " << binarycode << endl;

   cout << endl;

   input = 1;
   while (input != -1)
   {
	   cout << "Select a value to erase (enter -1 when finished): ";
	   cin >> input;
	   if (input != -1)
		   bin.erase(input);
	   else
		   break;
   }

   cout << endl;
   binarycode = bin.BinaryCode(1);
   cout << "The binary code for 1 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(2);
   cout << "The binary code for 2 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(3);
   cout << "The binary code for 3 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(4);
   cout << "The binary code for 4 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(5);
   cout << "The binary code for 5 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(6);
   cout << "The binary code for 6 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(7);
   cout << "The binary code for 7 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(8);
   cout << "The binary code for 8 is: " << binarycode << endl;
   binarycode = bin.BinaryCode(9);
   cout << "The binary code for 9 is: " << binarycode << endl;
   
   system("pause");
   return 0;
}
Exemplo n.º 23
0
void testPart2(){
	BinarySearchTree<BSTNode1<int>, int> tree = treeMaker(1);
	cout << tree.isBalanced() << endl << endl;
	BinarySearchTree<BSTNode1<int>, int> tree2 = treeMaker(2);
	cout << tree2.isBalanced() << endl << "END2" << endl;
}
Exemplo n.º 24
0
int main() {
    BinarySearchTree<int, int> bst;
    enum {QUIT, INSERT, SEARCH, INORDER, PREORDER, POSTORDER, SUCCESSOR, PREDECESSOR, DELETE, GETBYINDEX};
    int option = -1;
    int el;
    while (option != QUIT) {
        cout << "What you want to do now?"<<"\n";
        cout <<"0. QUIT 1. INSERT 2.SEARCH 3. INORDER 4. PREORDER 5.POSRORDER 6.SUCCESSOR 7.PREDECESSOR 8.DELETE 9.GETBYINDEX\n";
        cin >> option;
        switch (option) {
            case INSERT:    // 1
                {
                    int T;
                    cout << "Number of item to insert" << "\n";
                    cin >> T;
                    while (T-- > 0) {
                        cin >> el;
                        bst.insertNode(el, el);
                    }
                    break;
                }
            case SEARCH: // 2
                {
                    cout << "Value you want to search?" << "\n";
                    cin >> el;
                    Node<int,int>* node = bst.searchNode(el);
                    cout << "Searched node is " << node->getValue() << "\n";
                    break;
                }
            case INORDER: // 3
                cout << "Doing inorder traversal"<<"\n";
                bst.inOrder();
                cout << "\n";
                break;
            case PREORDER: // 4
                cout << "Doing preorder traversal"<<"\n";
                bst.preOrder();
                cout << "\n";
                break;
            case POSTORDER: // 5
                cout << "Doing postorder traversal"<<"\n";
                bst.postOrder();
                cout << "\n";
                break;
            case SUCCESSOR: // 6
                {
                    cout << "Whose successor are you looking for?"<<"\n";
                    cin >> el;
                    Node<int,int>* node = bst.successor(el);
                    cout << "Successor to node " << el << " is " << node->getValue() << "\n";
                    break;
                }
            case PREDECESSOR: // 7
                {
                    cout << "Whose predecessor are you looking for?"<<"\n";
                    cin >> el;
                    Node<int,int>* node = bst.predecessor(el);
                    cout << "Predecessor to node " << el << " is " << node->getValue() << "\n";
                    break;
                }
            case DELETE: // 8
                cout << "Which element you want to delete?"<<"\n";
                cin >> el;
                bst.deleteNode(el);
                break;
            case GETBYINDEX: // 9
                {
                    cout << "Enter Index of the item you are looking for?"<<"\n";
                    cin >> el;
                    Node<int,int>* node = bst.getNodeByIndex(el);
                    cout << "Item found is " <<node->getValue() << "\n";
                    break;
                }
            case QUIT: // 0
                cout<<"GoodBye!";
                return 0;
        }
    }
    return 0;
}
Exemplo n.º 25
0
int main()
{
    cout << "\n-------------------------------------------------------------------\n";


  srand(unsigned(time(0)));
  vector<int> myvector;

  cout << "Initializing a random vector with 1 million values";

  cout << endl << "Values are unique and inclue 1 and 1 million" << endl;
  // set some values:
  for (int i=1; i<=1000000; i++) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9

  // using built-in random generator:
  random_shuffle ( myvector.begin(), myvector.end() );

  // using myrandom:
  random_shuffle ( myvector.begin(), myvector.end(), myrandom);

  cout << '\n';
 //initializing two clock variables to measure execution time.
    clock_t t1,t2;
   cout << "---------------------------------------------------------------\n";
   /* For 2-3 B Tree */
   cout << "\nFor a 2-3 B Tree\n\n";
    cout << "Inserting unique values from 1 to 1,000,000 randomly\n";

    // start clock
    t1 = clock();

    BTree Bt(3); 
    
 for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) {
    Bt.insert(*it);
}
    t2 = clock();         // end clock

    float time_diff = ((float)t2-(float)t1);

    // converting the time to seconds before console printing
    // CLOCKS_PER_SEC is a macro from the time library
    cout << "Net time taken for insert:(in seconds) " << time_diff / CLOCKS_PER_SEC << endl << endl;


    // deleting values in the same order:

    cout << "\nDeleting values from 1 to 1,000,000 serially in ascending order\n";

    t1 = clock();

 for (int i = 1; i <= 1000000; i++) {
    Bt.remove(i);
}
    t2 = clock();         // end clock

    time_diff = ((float)t2-(float)t1);

    // converting the time to seconds before console printing
    // CLOCKS_PER_SEC is a macro from the time library
    cout << "net time taken for delete:(in seconds) " << time_diff / CLOCKS_PER_SEC << endl;

   cout << "**********************************************************************\n";
       /* For BinarySearch Tree */    

    cout << "For a BinarySearch Tree\n\n";
    cout << "Inserting unique values from 1 to 1,000,000 randomly\n";

    // start clock
    t1 = clock();

	BinarySearchTree bst;

   for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) {
    bst.insert(*it);
}
    t2 = clock();         // end clock

    time_diff = ((float)t2-(float)t1);

    // converting the time to seconds before console printing
    // CLOCKS_PER_SEC is a macro from the time library
    cout << "Net time taken for insert:(in seconds) " << time_diff / CLOCKS_PER_SEC << endl;


    // deleting values in the same order:

    cout << "\nDeleting values from 1 to 1,000,000 serially in ascending order\n";

    t1 = clock();

    for (int i = 1; i <= 1000000; i++ ){
    	bst.remove(i);
    }

    t2 = clock();         // end clock

    time_diff = ((float)t2-(float)t1);

    // converting the time to seconds before console printing
    // CLOCKS_PER_SEC is a macro from the time library
    cout << "Net time taken for delete:(in seconds) " << time_diff / CLOCKS_PER_SEC << endl;


    cout << "\n**********************************************************************\n";

     /* For an AVL Tree */    

    cout << "For a Red Black Tree\n\n";
    cout << "Inserting unique values from 1 to 1,000,000 randomly\n";

    // start clock
    t1 = clock();

	RedBlackTree<int> rbt;
   
   for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) {
    rbt.insert_key(*it);
}
    t2 = clock();         // end clock
 
    time_diff = ((float)t2-(float)t1);

    // converting the time to seconds before console printing
    // CLOCKS_PER_SEC is a macro from the time library
    cout << "Net time taken for insert:(in seconds) " << time_diff / CLOCKS_PER_SEC << endl;


    // deleting values in the same order:

    cout << "\nDeleting values from 1 to 1,000,000 serially in ascending order\n";

    t1 = clock();

    for (int i = 1; i <= 1000000; i++ ){
    	rbt.delete_key(i);
    }

    t2 = clock();         // end clock

    time_diff = ((float)t2-(float)t1);

    // converting the time to seconds before console printing
    // CLOCKS_PER_SEC is a macro from the time library
    cout << "Net time taken for delete:(in seconds) " << time_diff / CLOCKS_PER_SEC << endl;


    cout << "\n**********************************************************************\n";

     /* For an AVL Tree */    

    cout << "For an AVL Tree\n\n";
    cout << "Inserting unique values from 1 to 1,000,000 randomly\n";

    // start clock
    t1 = clock();

	AVLTree avlt;

   for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) {
    avlt.InsertNode(*it);
}
    t2 = clock();         // end clock

    time_diff = ((float)t2-(float)t1);

    // converting the time to seconds before console printing
    // CLOCKS_PER_SEC is a macro from the time library
    cout << "Net time taken for insert:(in seconds) " << time_diff / CLOCKS_PER_SEC << endl;


    // deleting values in the same order:

    cout << "\nDeleting values from 1 to 1,000,000 serially in ascending order\n";

    t1 = clock();

    for (int i = 1; i <= 1000000; i++ ){
    	avlt.RemoveNode(i);
    }

    t2 = clock();         // end clock

    time_diff = ((float)t2-(float)t1);

    // converting the time to seconds before console printing
    // CLOCKS_PER_SEC is a macro from the time library
    cout << "Net time taken for delete:(in seconds) " << time_diff / CLOCKS_PER_SEC << endl;


    cout << "\n**********************************************************************\n";



	
    return 0;
}
Exemplo n.º 26
0
 //Test program 3: BiIterator
int main( )
{
    BinarySearchTree<string> T;
    ifstream file("words.txt");

    if (!file)
    {
        cout << "couldn't open file words.txt" << endl;
        return 1;
    }

    vector<string> V1 = { istream_iterator<string>{file}, istream_iterator<string>{} };
    file.close();

    for(auto j: V1)
        T.insert( j );

    /**************************************/
    cout << "\nPHASE 1: contains\n\n";
    /**************************************/

    vector<string> V2 = { "airborne", "stop", "yelp", "Sweden", "obligations", "unbridled" };

    for(auto w: V2)
    {
        if( T.contains( w ) != T.end() )
            cout << "\""<< w << "\"" << " in the tree" << endl;
        else
            cout << "\""<< w << "\"" << " not in the tree" << endl;
    }

    /**************************************/
    cout << "\nPHASE 2: BiIterator, operator++\n\n";
    /**************************************/

    for(BinarySearchTree<string>::BiIterator it = T.begin(); it != T.end(); ++it)
    {
        cout << *it << endl;
    }


    cout << endl;

    /**************************************/
    cout << "PHASE 3: BiIterator, operator--\n\n";
    /**************************************/

    string largest = T.findMax( );

    for(auto it = T.contains( largest ); it != T.end(); --it)
    {
        cout << *it << endl;
    }

    cout << "\nFinished testing" << endl;


    /**************************************/
    cout << "PHASE 4: Frequency Table" << endl;
    /**************************************/

    BinarySearchTree<Word> T2;

    BinarySearchTree<Word>::BiIterator word_it;
    for(auto j: V1)
    {
        Word temp_word(j,-1);
        word_it = T2.contains(temp_word);
        if(word_it != BinarySearchTree<Word>::BiIterator())
            word_it->counter++;
        else
            T2.insert( Word(j,1) );

    }

    Word smallest = T2.findMin( );
    for(auto it = T2.contains( smallest ); it != T2.end(); ++it)
    {
        cout << setw(14) << it->key <<  "\t";
        cout << it->counter << endl;
    }


    return 0;
}
Exemplo n.º 27
0
int main()
{
    BinarySearchTree bst;
    bstNode* t = bst.Root();
    hcnode *h = NULL;
    hcnode a, b, c;
    int g=0;
    int t1=1;
    cout<<"enter '.' "<<"to end input"<<endl;
    while(t1)
    {                                                  //loop for input values
        cout<<"Enter char: ";
        cin>>a.c;
        if(a.c=='.')
        break;
        cout<<"Enter freq: ";
        cin>>a.freq;
        a.left = NULL;
        a.right = NULL;
        bst.add(t,a);
        g++;
    }
    if(g==1)                                          //if only one node is entered there is no traversal as why a code there is only one char;
    {
    	cout<<"only one element "<<endl;
    	exit(1);
    }

    while(!bst.check(t))                              //check upon number of nodes and finally only one bstnode remains with the hcnode with all data
    {
        a = bst.minimum(t);                           //gets first minimum hcnode from bst
        bst.del(t,a);                                //deletes the mininmum node from bst as it is already accessed
        b = bst.minimum(t);                           //next min node
        bst.del(t,b);                                 //del last node ie it is in hcnode b
        c = bst.minimum(t);                           //next min node
        bst.del(t,c);                                 //del last node ie it is in hcnode c
        add(h,a,b,c);                                 //adds the three nodes ie create a combined node
        bst.add(t,*h);                                //adds combined node to bst
    }
    int count=0;
    inorderc(t,count);                                    //if count is two add function has only two hcnodes
    if(count==2)
    {
    	if(t->lchild!=NULL)
    	{
    		add(h,t->data,t->lchild->data);               //h=node;a=node with max freq;b=node with less freq(h,a,b)
    	}
    	if(t->rchild!=NULL)
    	{
    		add(h,t->rchild->data,t->data);
    	}
    }
    hcnode*f=h;
    cout<<endl<<"printing level order "<<endl;
    levelorder(h);
    cout<<endl;
    string s;
    cout<<endl<<"Enter string: ";
    cin>>s;
    for(int i=0;i<s.length();i++)
    {
        if(s[i]=='1')
        {
            f = f->mid;
        }
        else if(s[i]=='0')
        {
            f = f->left;
        }
        else
        {
        	f=f->right;
        }
        if(f->left==NULL && f->right==NULL&&f->mid==NULL)
        {
            cout<<f->c;
            f = h;
        }
    }
    return 0;
}
Exemplo n.º 28
0
void heightAndNodes(const BinarySearchTree<ItemType>& BST, const string& treeName)
{
	cout << "\nHeight of " << treeName << " is " << BST.getHeight();
	cout << "\n\nNumber of nodes in " << treeName << " is " << BST.getNumberOfNodes();
}  // end heightAndNodes
Exemplo n.º 29
0
int main() {

//	test_big_three();
//	test_insert();
//	test_duplicate_count();
//	test_find_min();
//	test_find_max();
//	test_contains();
//	test_remove();
//	test_tree_height();
//	test_node_count();
//	test_count_total();

        int values[14] = {4,2,11,15,9,1,-6,5,3,15,2,5,13,14};
        BinarySearchTree bst;
        for (int i=0;i<14;i++) {
                bst.insert(values[i]);
        }
        cout << "Original tree " <<
                        "(asterisks denote a count of more than 1):\n";
        print_tree_details(bst);

        // make a copy with copy constructor
        BinarySearchTree bst_copy_constructor = bst;
        //bst_copy_constructor.print_tree();

        // make a copy with assignment overload
        BinarySearchTree bst_copy_1;
        bst_copy_1 = bst;

        cout << "Removing 9 from original tree:\n";
        bst.remove(9); // remove a node with no children
        print_tree_details(bst);

        bst = bst_copy_1;

        cout << "Removing 1 from original tree:\n";
        bst.remove(1); // remove a node with one child
        print_tree_details(bst);

        bst = bst_copy_1;

        cout << "Removing 11 from original tree:\n";
        bst.remove(11); // remove a node with one child
        print_tree_details(bst);

        bst = bst_copy_1;

        cout << "Removing 5 from original tree " <<
                        "(should still have one 5):\n";
        bst.remove(5); // remove a node with one child
        print_tree_details(bst);

        // check if the tree contains values
        bst = bst_copy_1;
        for (int i=-10;i<20;i++) {
                cout << "Tree " << (bst.contains(i) ?
                                "contains " :
                                "does not contain ")
                                << "the value " << i << "\n";
        }

        cout << "\nFinished!\n";
        return 0;
}
Exemplo n.º 30
0
int main()
{
	{
		BinarySearchTree<int> t;
		t.insert(8);t.insert(3);t.insert(10);t.insert(1);
		t.remove(1);t.remove(3);
		t.insert(6);t.insert(14);t.insert(4);t.insert(7);t.insert(13);

        assert( t.find(13)->val == 13);
        assert( t.findMax()->val == 14);
        assert( t.findMin()->val == 4);

		t.traverse(printNode);
	}

	{
		BinarySearchTree<int> t;
		t.insert(8);t.insert(3);t.insert(10);t.insert(1);
		t.insert(6);t.insert(14);t.insert(4);t.insert(7);t.insert(13);

		t.traverse(printNode);
	}

	return 0;
}