예제 #1
0
//Main function
int main()
{
	AVL *a = new AVL();
	string str;
	int val;
	cin >> str;	
	clock_t start, end;
	start = clock();
	while(!cin.eof())
	{
		if(str.compare("insert") == 0)
		{
			cin >> val;
			if((a->access(val)) == true)
				cout << "Element already inserted" << endl;
			else
			{
				a->insert(val);
				cout << "Element inserted" << endl;
			}
		}
		
		if(str.compare("access") == 0)
		{
			cin >> val;
			if((a->access(val)) == true)
				cout << "Element accessed" << endl;
			else
				cout << "Element not found" << endl;
		}
예제 #2
0
int main() {
    AVL avl;
    avl.insert(5);
    avl.print();
    avl.insert(3);
    avl.print();
}
예제 #3
0
파일: avlhash.cpp 프로젝트: Mengqi/Cpp
int AVLHash :: search(int k)
{
        int pos = hashCode(k);
        AVL *tree = hash_table[pos];

        return tree->search(k);
}
예제 #4
0
파일: avlhash.cpp 프로젝트: Mengqi/Cpp
void AVLHash :: insert(int k, int v)
{
        int pos;
        AVL *tree;

        pos = hashCode(k);
        tree = hash_table[pos];
        tree->insert(k, v);
}
예제 #5
0
void printTreeStatus(const AVL<T> &t) {
    cout << "----------------------------------------" << endl;
    if (t.isEmpty()) cout << "The tree is empty" << endl;
    else {
        cout << "Tree root is: " << t.root() << endl;
        cout << "Tree height is: " << t.height() << endl;
        cout << "Tree contains " << t.size() << " elements" << endl;
    }
    cout << "----------------------------------------" << endl;
}
예제 #6
0
파일: main.cpp 프로젝트: mboghiu/try
int main()
{
    while (true)
    {
        ///////////// Read user input ////////////

        std::string command, value;
        size_t key;

        utils::read_input<size_t, std::string>(std::cin, command, key, value);

        ///////////// Process ///////////

        switch (utils::str2enum(command))
        {
            case options::LS:
            {
                g_avl.Print();
                break;
            }

            case options::ADD:
            {
                g_avl.insert(key, value);
                break;
            }

            case options::RM:
            {
                g_avl.remove(key);
                break;
            }

            case options::GET:
            {
                try
                {
                    std::cout << key << " = " << g_avl.lookup(key) << std::endl;
                }
                catch (const std::string& e)
                {
                    std::cout << "error: " << e << std::endl;
                }

                break;
            }

            case options::Q: { exit(0); break; }
            
            case options::UNKNOWN: { break; }
        }
    }

    return 0;
}
예제 #7
0
int main()
{
    int n,x;
    AVL <int> avl;
    cout<<"input the number of elements:";
    cin>>n;
    for(int i=0;i<n;i++)
    cin>>x,avl.insert(x);
    avl.print();
    return 0;
}
예제 #8
0
int main(void){
   AVL tree;
   tree.insert(10);
   tree.insert(30);
   tree.insert(20);
   tree.insert(15);
   tree.insert(18);
   tree.insert(16);
   cout << "*************************" << endl;
   tree.inOrderPrint();
      
}
예제 #9
0
int main(void){
	AVL avl;
	avl.insert(10);
	avl.insert(5);
	avl.insert(20);
	avl.insert(3);
	avl.insert(15);
	avl.insert(8);
	avl.insert(25);
	avl.insert(7);
	avl.insert(2);
	avl.insert(9);
	avl.insert(6);
}
예제 #10
0
int main(){
	FileIO * file = new FileIO("tube.txt");

	vector<Station *> station_list = file->read_file_to_station_list();
	vector<Station *> sorted_list = file->read_file_to_station_list();
	std::sort(sorted_list.begin(), sorted_list.end(), sort_by_name);
//	print_all(sorted_list, station_list);

//	search_by_keyword(sorted_list, station_list);
//	mode_selection(sorted_list, station_list);
	//test section

	node<int> *_node = new node<int>();
//	cout<<sorted_list[0]->get_station_index()<<endl;
	_node->data = sorted_list[0]->get_station_index();
	AVL<int> *tree = new AVL<int>(_node); //new binary_tree<int>(_node);

	for(vector<Station *>::iterator it = sorted_list.begin() + 1;it != sorted_list.end();++it){
		bool b_return = tree->insert((*it)->get_station_index());
//		cout<<(*it)->get_station_index()<<"  "<<b_return<<endl;
	}
	cout<<"done!"<<endl;
//	tree->traverse_inorder(tree->root);
	cout<<"Tree height is "<<tree->tree_height<<endl;
	node<int> *returned_node = tree->search(0);
	cout<<returned_node->data<<" "<<returned_node->height<<endl;
	node<int> *rhs = tree->root;
//	cout<<rhs->data<<" "<<rhs->height<<endl;
	rhs = rhs->rhs;
	node<int> min, max;
//	cout<<"d 1"<<endl;
	tree->find_min_from(rhs, min);
//	cout<<"d 2"<<endl;
	tree->find_max_from((tree->root)->lhs, max);
	cout<<"min in right branch is "<<min.data<<" "<<min.height<<endl;
	cout<<"max in left branch is "<<max.data<<" "<<max.height<<endl;

	cout<<"depth is "<<tree->find_depth(tree->root)<<endl;
	cout<<"left branch depth is "<<tree->find_depth((tree->root)->lhs)<<endl;
	cout<<"right branch depth is "<<tree->find_depth((tree->root)->rhs)<<endl;
	cout<<"balance factor is "<<tree->balance_factor(tree->root)<<endl;
	cout<<"tree is balanced? "<<tree->is_balanced(tree->root)<<endl;

	cout<<"tree root "<<(tree->root)->data<<endl;
//	delete[] tree->root;
	delete tree;
	return 0;
}
예제 #11
0
signed ARC033_C(){
  int q;
  cin>>q;
  AVL<Int> avl;
  for(int i=0;i<q;i++){
    int t,x;
    cin>>t>>x;
    if(t==1) avl.insert(x);
    else{
      Int key=avl.rank(x-1)->key;
      cout<<key<<endl;
      avl.erase(key);
    }
  }
  return 0;
}
예제 #12
0
signed ARC028_B(){
  int n,k;
  cin>>n>>k;
  int x[n];
  for(int i=0;i<n;i++) cin>>x[i];
  map<int,int> m;
  for(int i=0;i<n;i++) m[x[i]]=i+1;
  AVL<Int> avl;
  for(int i=0;i<k-1;i++) avl.insert(x[i]);
  for(int i=k-1;i<n;i++){
    avl.insert(x[i]);
    Int key=avl.rank(k-1)->key;
    cout<<m[key]<<endl;
    assert(avl.index(key)==k-1);
  }
  return 0;
}
예제 #13
0
/**** Programa Principal ******************************************************/
int main(){
    //Variables locales
    AVL<int> v;
    int e;
    int op=0;
	while (op!=12)
	{
		cout<<"________________________________________________________________________________"<<endl
		<<"                                 ADT Arbol AVL"<<endl
		<<"________________________________________________________________________________"<<endl<<endl
		<<"             ___________________________________________________________"<<endl
		<<"            |      [ 1 ]  Meter elemento                                |"<<endl
		<<"            |      [ 2 ]  Sacar elemento                                |"<<endl
		<<"            |      [ 3 ]  Inorden                                       |"<<endl
		<<"            |      [ 4 ]  Preorden                                      |"<<endl
		<<"            |      [ 5 ]  Postorden                                     |"<<endl
		<<"            |      [ 6 ]  Inorden Inv.                                  |"<<endl
		<<"            |      [ 7 ]  Preorden Inv                                  |"<<endl
		<<"            |      [ 8 ]  Postorden Inv                                 |"<<endl
		<<"            |      [ 9 ]  Hijos                                         |"<<endl
		<<"            |      [ 10 ]  Camino                                       |"<<endl
		<<"            |      [ 11 ]  Altura                                       |"<<endl
		<<"            |___________________________________________________________|"<<endl<<endl
		<<"             Opcion a Elegir: ";
		
		cin>>op;
		system("cls");

		if (op==1)
		{
                  
            cout<<"Dame un numero a insertar ";          
            cin>>e;           
			v.meter(e);
			system("pause");
			system("cls");
		}
		if (op==2)
		{
                  
            cout<<"Dame un numero a sacar ";          
            cin>>e;           
			v.sacar(e);
			system("pause");
			system("cls");
		}
예제 #14
0
bool isInOrder(AVL<T> const &in) {
  vector<T> list = in.inOrder();
  for (auto it = list.begin() + 1; it < list.end(); it++) {
    if (*it < *(it - 1))
      return false;
  }
  return true;
}
예제 #15
0
int main() {
  AVL<int>* avl = new AVL<int>();
  //AVL<double>* avlD = new AVL<double>();
  //AVL<std::string>* avlS = new AVL<std::string>();
  
  cout << "Pre Order Traversal Print" << endl;
  cout << endl;
  avl->insert(4);
  avl->insert(2);
  avl->insert(3);
  avl->insert(7);
  avl->insert(1);
  avl->insert(17);
  avl->insert(16);
  avl->insert(5);
  avl->print();
  cout << endl;
/*
  cout << "Post Order Traversal" << endl;
  avl->postOrderTraversal();
  cout << endl;
  
  cout << "In Order Traversal" << endl;
  avl->inOrderTraversal();
  cout << endl;
  cout << "End!" << endl;*/
}
예제 #16
0
/******************************************************************************************
 * Test an AVL
 ******************************************************************************************/
template <typename T> void  testAVL(int n) {
   AVL<T>* avl = new AVL<T>;
   while (avl->size() < n) {
      T e = dice((T)n*3); //[0, 3n)范围内的e
      switch (dice(3)) {
         case 0: { //查找,成功率 <= 33.3%
            printf("Searching for "); print(e); printf(" ...\n");
            BinNodePosi(T) & p = avl->search(e);
            p ?
               printf("Found with"), print(p), printf("\n") :
               printf("Not found\n");
            break;
         }
         case 1: { //删除,成功率 <= 33.3%
            printf("Removing "); print(e); printf(" ...\n");
            avl->remove(e) ? printf("Done\n"), print(avl) : printf("Not exists\n");
            break;
         }
         default: {//插入,成功率 == 100%
            printf("Inserting "); print(e); printf(" ...\n");
            BinNodePosi(T) p = avl->insert(e);
            printf("Done with"), print(p), printf("\n"), print(avl);
            break;
         }
      }
   }
   while (avl->size() > 0) {
      T e = dice((T)n*3); //[0, 3n)范围内的e
      printf("Removing "); print(e); printf(" ...\n");
      avl->remove(e) ? printf("Done\n"), print(avl) : printf("Not exists\n");
   }
   release(avl);
}
예제 #17
0
int main()
{
	AVLNode* checkRoot = new AVLNode();
	AVLNode* mispelledRoot = new AVLNode();
	AVL* checkTree = new AVL();
	AVL* mispelledTree = new AVL();
	
	std::ifstream dictionary; 

	std::string dictonaryFile = "D:\\DataStructures\\Searching\\Searching\\dictionary.txt";

	dictionary.open(dictonaryFile);

	checkRoot = checkTree->InputData(dictionary);

	checkTree->PrintTree(checkRoot);

	//read dictionary file -> save all into a AVL tree

	system("PAUSE");
}
예제 #18
0
int main( void ) {
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    AVL<segment> Tree;
    int n;
    cin >> n;
    vector<segment> seg;
    for (int i = 0; i < n; i++) {
        point pointOne, pointTwo;
        cin >> pointOne.x >> pointOne.y >> pointTwo.x >> pointTwo.y;
        seg.push_back(segment(pointOne, pointTwo));
    }

    vector<point_event> e;
    for (int i = 0; i < n; i++) {
        e.push_back(point_event(min(seg[i].pointOne.x, seg[i].pointTwo.x), 1, i));
        e.push_back(point_event(max(seg[i].pointOne.x, seg[i].pointTwo.x), -1, i));
    }
    sort(e.begin(), e.end());
    double val = numeric_limits<double>::max();
    segment zero(point(val, val), point(val, val));
    for (int i = 0; i < e.size(); i++) {
        int ind = e[i].ind;
        if (e[i].type == 1) {
            Tree.Add(seg[ind]);
            segment cur = Tree.Next(seg[ind]);
            if (!(cur == zero) && crossing(cur, seg[ind])) {
                cout << "Еть пересечение";
                return 0;
            }
            cur = Tree.Prev(seg[ind]);
            if (!(cur == zero) && crossing(cur, seg[ind])) {
                cout << "Есть пересечиние";
                return 0;
            }

        }
        else {
            segment cur = Tree.Next(seg[ind]);
            if (!(cur == zero) && crossing(cur, seg[ind])) {
                cout << "Еть пересечение";
                return 0;
            }
            cur = Tree.Prev(seg[ind]);
            if (!(cur == zero) && crossing(cur, seg[ind])) {
                cout << "Есть пересечиние";
                return 0;
            }
            Tree.Delete(seg[ind]);
        }
    }
    cout << "Нет пересечений";
    return 0;
}
예제 #19
0
int main()
{
	AVL avltree;
	int tc;
	int i, j, n, k;
	scanf("%d", &tc);
	while (tc--)
	{
		avltree.Init();
		scanf("%d %d", &k, &n);
		printf("%d %d\n", k, (n+1)/2);
		j = 0;
		for (i = 0; i < n; i++)
		{
			scanf("%d", &k);
			avltree.Insert(k);
			if (i % 2 == 0)
			{
				k = avltree.GetMiddle();
				if (j < 9)
				{
					printf("%d ", avltree.tree[k]);
					j++;
				}
				else
				{
					printf("%d\n", avltree.tree[k]);
					j = 0;
				}
			}
		}
		if (j > 0)
		{
			printf("\n");
		}
	}	
	return 0;
}
예제 #20
0
int main()
{
    AVL b;
    int n, k;
    cin >> n;
    for (int i = 0; i < n; i++) {
       cin >> k;
       b.insert(k, &b.root);
    }
    b.print(b.root);
   // cout << endl << b.search(2, b.root) << endl;
    cout << "enter number of queries for del" << endl;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cout << "enter what to del\n";
        cin >> k;
        b.delete_it(k, &b.root);
        cout << endl;
        b.print(b.root);
    }

    return 0;
}
예제 #21
0
int main(int argc, char **argv)
{
	int i, j, n;
	double t;
	AVL<int> tree;
	if (argc > 3) return EXIT_FAILURE;
	i = time(0);
	if (argc == 1) n = 20;
	else {
		n = atoi(argv[1]);
		if (argc == 3) i = atoi(argv[2]);
	}
	srand((unsigned int)i);
	cout << "Size is " << n << endl;
	cout << "Seed is " << i << endl;
	cout << "Inserting..." << endl;
	t = ((double)clock())/CLOCKS_PER_SEC;
	for (i = 1 ; i <= n ; i++) {
		j = rand()%n+1;
	//	cout << j << ' ';
		tree.insert(j);
	}
	t = ((double)clock())/CLOCKS_PER_SEC-t;
	cout << t << " secs" << endl;
//	cout << "\nPrinting tree..." << endl;
//	tree.print();
	cout << "Size of tree is: " << tree.size() << endl;
	ofstream out("avl.dot");
	tree.display(out);
	out.close();
	system("dot avl.dot -Tpng -o avl.png");
	cout << "Created tree image at avl.png!" << endl;
	cout << "Extracting..." << endl;
	t = ((double)clock())/CLOCKS_PER_SEC;
	for (i = 1 ; i <= n ; i++) {
		j = rand()%n+1;
	//	cout << j << ' ';
		tree.extract(j);
	}
	t = ((double)clock())/CLOCKS_PER_SEC-t;
	cout << t << " secs" << endl;
//	cout << "\nPrinting tree..." << endl;
//	tree.print();
	cout << "Size of tree is: " << tree.size() << endl;
	cout << "Clearing..." << endl;
	t = ((double)clock())/CLOCKS_PER_SEC;
	tree.clear();
	t = ((double)clock())/CLOCKS_PER_SEC-t;
	cout << t << " secs" << endl;
	return EXIT_SUCCESS;
}
예제 #22
0
//I used a .txt filled with employees names and ID numbers to create the AVL binary tree.
int main() 
{
    std::string file_name = "data/employees.txt";
    std::ifstream in_file(file_name);
    
    AVL <std::string, std::string> EmployeeData;
    
    //Parse the employee names and idss out of the text file
    std::string line;
    while(std::getline(in_file,line)) 
    {
        // Gets the employees name
        std::string employee_name = line.substr(0,line.find(","));
        // Gets the employees id number
        std::string employee_id = line.substr(line.find(",")+1);
        EmployeeData.insert(employee_name, employee_id);
    }
    //EmployeeData.Delete(EmployeeData.root, "Zyon Newman");
    EmployeeData.print(EmployeeData.root);
    std::cout << "Testing Lookup" << std::endl;
    std::cout << "Zyler Whitney: " << EmployeeData.lookup(EmployeeData.root, "Zyler Whitney") << std::endl;

    return 0;
}
예제 #23
0
파일: avl.cpp 프로젝트: bpan2/dsa555-w15
int main(void){
	AVL tree;
	tree.insert(10);
	tree.insert(20);
	tree.print();
	tree.insert(30);
	cout << "*********************" << endl;
	tree.print();
	for(int i=40;i< 70;i+=10){
		tree.insert(i);
		cout << "*********************" << endl;
		tree.print();
	}
//	tree.depthFirstPrint();

}
예제 #24
0
int main()
{
    int values[N];

    AVL<int> avl;

    cout << "Populating the tree with " << N << " random values... ";
    for (unsigned i = 0; i < N; ++i) {
        values[i] = rand();
        avl.insert(values[i]);
    }
    cout << "Done" << endl;

    printTreeStatus(avl);

    for (unsigned i = 0; i < N; ++i) {
        unsigned idx = rand() % N;
        if (!avl.contains(values[idx])) 
	        cout << "ERROR: Value " << values[idx] << " was inserted and not found!" << endl;
    }

    cout << "Now removing a random element from the tree... ";
    unsigned idx = rand() % N;
    avl.erase(values[idx]);
    cout << "Done" << endl;

    printTreeStatus(avl);
    
    cout << "Now removing the root of the tree " << N_ELEMS_TO_REMOVE << " times... ";
    for (unsigned i = 0; i < N_ELEMS_TO_REMOVE; ++i) {
        avl.erase(avl.root());
    }
    cout << "Done" << endl;

    printTreeStatus(avl);

    // Outputting to cerr so the output can be redirected with ./avl_demo 2> <name>.gvz
    cout << "Do you want to output the GraphViz representation of the tree to the cerr stream (Y/n)? ";
    char usrInput;
    cin >> usrInput;
    if (usrInput == 'Y' || usrInput == 'y') avl.toGraphViz(cerr, "AVL");
    
    return 0;
}
예제 #25
0
main(){

	int length = 6;
	int a[6] = {1,2,3,4,5,6};
	AVL tree;
	tree.Binarify(a,length);
	cout<<"============================================================="<<endl<<endl;
	cout<<"Displaying the Binary Sorted tree :- "<<endl;
	tree.DisplayTree();
	cout<<"============================================================="<<endl<<endl;
	cout<<"Heights of nodes in the AVL: "<<endl;
	tree.DisplayTreeWithHeights();
	cout<<"Size of Binary Tree = "<<(tree.head)->size<<endl;
	cout<<"============================================================="<<endl<<endl;
	cout<<"Displaying Tree with Heights after Rotating about 4"<<endl;
	tree.LeftRotateAbout(tree.find(1));
	tree.DisplayTreeWithHeights();
	cout<<"Size of Binary Tree = "<<(tree.head)->size<<endl;
	cout<<"============================================================="<<endl<<endl;
	cout<<"Displaying Tree with Heights after again Rotating about 4"<<endl;
	tree.LeftRotateAbout(tree.find(2));
	tree.DisplayTreeWithHeights();
	cout<<"Size of Binary Tree = "<<(tree.head)->size<<endl;
	cout<<"============================================================="<<endl<<endl;
	cout<<"Displaying Tree with Heights after again Rotating about 2"<<endl;
	tree.LeftRotateAbout(tree.find(4));
	tree.DisplayTreeWithHeights();
	cout<<"Size of Binary Tree = "<<(tree.head)->size<<endl;
	cout<<"============================================================="<<endl<<endl;
	cout<<"Size of Binary Tree = "<<(tree.head)->size<<endl;
	cout<<"============================================================="<<endl<<endl;
	cout<<"Finding if 13 is a member of tree :- "<<tree.find(13)<<endl;
	cout<<"Finding if 2 is a member of tree :- "<<tree.find(2)<<endl;
	cout<<"============================================================="<<endl<<endl;
	cout<<"Finding number of nodes less than 9 :-  "<<tree.NodesLessThan(9)<<endl;
	cout<<"============================================================="<<endl<<endl;
}
예제 #26
0
파일: main.cpp 프로젝트: tuffk/arboles
int main(int argc, const char * argv[])
{
	/*
	ArbolBinario<int> * ab = new ArbolBinario<int>();

	Nodo<int> *raiz = new Nodo<int>(5);
	ab->insertar(NULL, 1, raiz);

	Nodo<int> *n1 = new Nodo<int>(8);
	ab->insertar(raiz, 1, n1);

	Nodo<int> *n2 = new Nodo<int>(10);
	ab->insertar(raiz, 0, n2);

	Nodo<int> *n3 = new Nodo<int>(11);
	ab->insertar(n2, 1, n3);

	Nodo<int> *n4 = new Nodo<int>(25);
	ab->insertar(n1, 1, n4);

	Nodo<int> *n5 = new Nodo<int>(30);
	ab->insertar(n1, 1, n5);

	std::cout << *ab << std::endl;

	Nodo<int> * buscado = ab->buscar(25);

	if (buscado != NULL) {
	std::cout << "El nodo SI se encuentra y su valor es = " << *buscado << std::endl;
	}
	else {
	std::cout << "El nodo NO se encuentra" << std::endl;
	}

	if (ab->sonHermanos(8, 10)) {
	std::cout << "Son hermanos" << std::endl;
	}
	else {
	std::cout << "No son hermanos" << std::endl;
	}

	//cout << *n4 <<endl;

	std::cout << "Nivel de " << *n4 << " = " << ab->nivel(n4) << std::endl;

	ab->primos(n3);

	std::cout << "Número de nodos: " << ab->size() << std::endl;

	//probando ancestro
	cout<< *n1 << " es ancestro de " << *n4 << " = " << ab->esAncestro(n4,n1) << endl;

	//probando metodo de desendiente
	cout<< *n4 << " es desendiente de " << *n1 << " = " << ab->esDesendiente(n1,n4) << endl;

	//probando imprime ancestros
	ab->ancestros(n3);

	//probando imprime desendientes
	cout << "desendientes de " << * n1 << endl;
	ab->desendientes(n1, false);
	cout << endl;

	ab->caminoMasLargo();


	ab->clear();

	std::cout << "Número de nodos: " << ab->size() << std::endl;
	*/

	srand((int)time(NULL));
	AVL<int>* ab = new AVL<int>();


	clock_t t;
	t = clock();



	for (int i = 0; i < 1000; i++)
	{
		cout << i << " ";
		Nodo<int>* nod = new Nodo<int>(i);
		ab->insertar(nod);
	}




	t = clock() - t;
	//printf("It took me %d clicks (%f seconds).\n", t, ((float)t) / CLOCKS_PER_SEC);
	cout << "tardo " << t << " clicks, y " << (((float)t) / CLOCKS_PER_SEC) << " segundos" << endl;

	system("PAUSE");

	//delete ab;

	return 0;
}
예제 #27
0
int main() {
   
  int SIZE=20;
  vector<int> v(SIZE);  
  AVL<int>* avl = new AVL<int>();
  srand(time(0));  

  for (int i=0;i<SIZE;i++) {
    v[i] = 5*i;
  }
  random_shuffle(v.begin(),v.end());

  cout << "Multiples of 5 from 0 to 95 have been shuffled." << endl;
  cout << "They will be inserted into an AVL tree in the following order:" << endl << endl;  
  for (int i=0;i<SIZE;i++) {
    cout << v[i] << endl;
  }
  cout << endl;

  for (int i=0;i<SIZE;i++) {
    avl->insert(v[i]);
    cout << "After Inserting " << v[i] << endl << endl;
    avl->print();
  }
  cout << "In Order Traversal: " << endl;
  avl->inOrderTraversal();
  cout << endl << "Post Order Traversal: " << endl;
  avl->postOrderTraversal();
  cout << endl;
  
  cout << "Now the shuffled numbers will be removed from the AVL tree ";
  cout << "in the order they were inserted." << endl << endl;
  for (int i=0;i<SIZE;i++) {
    avl->remove(v[i]);
    cout << "After Removing " << v[i] << endl << endl;
    avl->print();
  }
  
  avl->removeTree(); 
  srand(time(0)); 

  cout << "Now 20 random numbers between 0 and 99 will be inserted into an AVL tree in this order.";
  cout << endl;
  for (int i=0;i<SIZE;i++) {
    v[i] = rand() % 100;
    cout << v[i] << endl;
  }
  cout << endl;
  
  for (int i=0;i<SIZE;i++) {
    avl->insert(v[i]);
    cout << "After Inserting " << v[i] << endl << endl;
    avl->print();
  }

  cout << "In Order Traversal: " << endl;
  avl->inOrderTraversal();
  cout << endl << "Post Order Traversal: " << endl;
  avl->postOrderTraversal();
  cout << endl;
  
  for (int i=0;i<SIZE;i++) {
    avl->remove(v[i]);
    cout << "After Removing " << v[i] << endl << endl;
    avl->print();
  }

  avl->removeTree();

  cout << "Now the numbers from 1 to 20 will be inserted into an AVL tree in order." << endl;
  cout << "They will be removed in the same order." << endl;
  for (int i=0;i<SIZE;i++) {
    v[i] = i+1;
    cout << v[i] << endl;
  }
  cout << endl;

  for (int i=0;i<SIZE;i++) {
    avl->insert(v[i]);
    cout << "After Inserting " << v[i] << endl << endl;
    avl->print();
  }

  cout << "In Order Traversal: " << endl;
  avl->inOrderTraversal();
  cout << endl << "Post Order Traversal: " << endl;
  avl->postOrderTraversal();
  cout << endl;
  
  for (int i=0;i<SIZE;i++) {
    avl->remove(v[i]);
    cout << "After Removing " << v[i] << endl << endl;
    avl->print();
  }

  avl->removeTree();

  cout << "Now the numbers from 1 to 20 will be inserted into an AVL tree in order." << endl;
  cout << "They will be removed in REVERSE order." << endl;
  for (int i=0;i<SIZE;i++) {
    v[i] = i+1;
    cout << v[i] << endl;
  }
  cout << endl;

  for (int i=0;i<SIZE;i++) {
    avl->insert(v[i]);
    cout << "After Inserting " << v[i] << endl << endl;
    avl->print();
  }

  cout << "In Order Traversal: " << endl;
  avl->inOrderTraversal();
  cout << endl << "Post Order Traversal: " << endl;
  avl->postOrderTraversal();
  cout << endl;
  
  for (int i=0;i<SIZE;i++) {
    avl->remove(v[SIZE-1-i]);
    cout << "After Removing " << v[SIZE-1-i] << endl << endl;
    avl->print();
  }

  delete avl;


/*
  AVL<int>* avl = new AVL<int>();
  avl->insert(1);
  avl->insert(2);
  avl->print();
  avl->insert(3);
  avl->print();
  avl->insert(4);
  avl->print();
  avl->insert(5);
  avl->print();
  avl->insert(6);
  avl->print();
  avl->insert(7);
  avl->print();
  avl->insert(8);
  avl->insert(9);
  avl->print();  
  avl->insert(10);
  avl->print();
  avl->inOrderTraversal();
  avl->postOrderTraversal();

  
  avl->remove(1);
  avl->print();  
  avl->remove(2);
  avl->print();  
  avl->remove(3);
  avl->print();  
  avl->remove(4);
  avl->print();
  avl->remove(5);
  avl->print();  
  avl->remove(6);
  avl->print();  
  avl->remove(7);
  avl->print();  
  avl->remove(8);
  avl->print();
  avl->remove(9);
  avl->print();
  avl->remove(10);
  avl->print();  

  avl->insert(5);
  avl->print();
  avl->insert(18);
  avl->print();
  avl->insert(25);
  avl->insert(2);
  avl->insert(1);
  avl->print();
  avl->remove(18);
  avl->print();
  delete avl;

  AVL<int>* a = new AVL<int>();
  a->insert(400);
  a->print();
  a->remove(5);
  a->print();
  a->remove(400);
  a->print();
  delete a;
*/

/*
  AVL<double>* d = new AVL<double>();
  d->insert(1);
  d->insert(2);
  d->insert(4);
  d->print();
  d->insert(3.5);
  d->insert(5);
  d->print();
  d->insert(3.25);
  d->print();

  delete d;

  AVL<int>* a1 = new AVL<int>();
  a1->insert(10);
  a1->insert(20);
  a1->insert(30);
  a1->insert(40);
  a1->print();
  a1->insert(35);
  a1->print();
  delete a1;

  AVL<int> a2;
  a2.insert(3);
  a2.insert(2);
  a2.insert(1);
  a2.insert(4);
  a2.print();
  a2.insert(5);
  a2.print();
  a2.insert(6);
  a2.print();
  a2.insert(7);
  a2.print();
  a2.insert(16);
  a2.print();
  a2.insert(15);
  a2.print();
  a2.insert(14);
  a2.print();
  a2.remove(7);
  a2.print();
  a2.remove(4);
  a2.print();
*/
/*
  AVL<double>* db=new AVL<double>();
  db->insert(7.5);
  db->insert(12.98);
  db->insert(3.45);
  db->insert(-2.58);
  db->insert(99.1);
  db->print();
  db->remove(12.98);
  db->remove(7.5);
  db->remove(5.34353);
  db->print();
  delete db;

  AVL<int>* b=new AVL<int>();
  b->insert(10);
  b->insert(5);
  b->insert(15);
  b->insert(1);
  b->insert(7);
  b->insert(11);
  b->insert(17);
  b->insert(18);
  b->insert(12);
  b->insert(14);
  b->insert(19);
  b->insert(8);
  b->insert(9);

  b->print();
 
  b->remove(15);
  b->remove(12);
  b->remove(10);
  b->print();
  b->remove(19);
  b->print();

  delete b;
*/

}
예제 #28
0
int _tmain(int argc, _TCHAR* argv[])
{
	//Binary Search Tree
	int bstArraySize = 11;		
	int bstArray[] = { 15, 6, 18, 3, 7, 17, 20, 2, 13, 4, 9 };
	cout << "BST Input Array: " ;
	PrintArray(bstArray, bstArraySize);

	BST myBST;
	for (int i = 0; i < bstArraySize; i++)
		myBST.Insert(myBST.root, bstArray[i]);

	cout << "InOrderTreeWalk: ";
	myBST.InOrderTreeWalk(myBST.root);
	cout << endl;

	cout << "PreOrderTreeWalk: ";
	myBST.PreOrderTreeWalk(myBST.root);
	cout << endl;

	cout << "PostOrderTreeWalk: ";
	myBST.PostOrderTreeWalk(myBST.root);
	cout << endl;

	myBST.Search(myBST.root, 100);
	myBST.Search(myBST.root, 20);
	myBST.Maximum(myBST.root);
	myBST.Minimum(myBST.root);
	myBST.SearchParent(myBST.root, 9);

	cout << "Delete Node 15: ";
	myBST.Delete(myBST.root, 15);	
	myBST.InOrderTreeWalk(myBST.root);
	cout << endl;
	cout << endl;

	//Max Heap
	int table[] = {16, 4, 10, 14, 7, 9, 3, 2, 8, 1, 0, 0, 0, 0};
	int heapSize = 10;
	int* maxHeapArray = new int[15];

	for (int i = 0; i < heapSize; i++)
		*(maxHeapArray + i) = table[i];
	cout << "Max-Heap: ";
	PrintArray(maxHeapArray, heapSize);
	MaxHeap myMaxHeap;
	myMaxHeap.MaxHeapify(maxHeapArray, heapSize, 1);
	cout << "Max-Heapified 1: ";
	PrintArray(maxHeapArray, heapSize);

	for (int i = 0; i < heapSize; i++)
		*(maxHeapArray + i) = table[i];
	cout << "Max-Heap: ";
	PrintArray(maxHeapArray, heapSize);
	myMaxHeap.BuildHeap(maxHeapArray, heapSize);
	cout << "BuildHeap: ";
	PrintArray(maxHeapArray, heapSize);
	cout << "HeapExtractMax: " << myMaxHeap.HeapExtractMax(maxHeapArray, heapSize) << endl;
	cout << "Remaining: ";		
	PrintArray(maxHeapArray, heapSize - 1);
	cout << "HeapInsert 32: \n";
	myMaxHeap.HeapInsert(maxHeapArray, heapSize - 1, 32);
	cout << "New Heap: ";
	PrintArray(maxHeapArray, heapSize);

	for (int i = 0; i < heapSize; i++)
		*(maxHeapArray + i) = table[i];
	cout << "Max-Heap: ";
	PrintArray(maxHeapArray, heapSize);
	myMaxHeap.HeapSort(maxHeapArray, heapSize);
	cout << "HeapSort: ";
	PrintArray(maxHeapArray, heapSize);
	cout << endl;

	//AVL tree
	int avlArraySize =11;
	//int avlArray[] = { 15, 6, 18, 3, 7, 17, 20, 2, 13, 4, 9 };
	int avlArray[] = { 30, 50, 40, 60, 70, 17, 20, 2, 13, 4, 9 };
	cout << "AVL Input Array: ";
	PrintArray(avlArray, avlArraySize);
	AVL myAVL;
	for (int i = 0; i < avlArraySize; i++)
	{
		myAVL.Insert(myAVL.root, avlArray[i]);
		myAVL.InOrderTreeWalk(myAVL.root);
		cout << endl;
	}

	cout << "Delete 30: \n";
	myAVL.Delete(myAVL.root, 30);
	myAVL.InOrderTreeWalk(myAVL.root);
	cout << endl;

	cout << "Delete 13: \n";
	myAVL.Delete(myAVL.root, 13);
	myAVL.InOrderTreeWalk(myAVL.root);
	cout << endl;

	cout << "Delete 20: \n";
	myAVL.Delete(myAVL.root, 20);
	myAVL.InOrderTreeWalk(myAVL.root);
	cout << endl;

	//RB tree
	int rbArraySize = 11;
	//int rbArray[] = { 1, 3, 2, 4, 5, 6, 8, 7, 9, 10, 11 };
	int rbArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
	cout << "RB Input Array: ";
	PrintArray(rbArray, rbArraySize);

	RB myRB;
	for (int i = 0; i < rbArraySize; i++)
	{
		myRB.Insert(myRB.root, myRB.root, rbArray[i]);
		myRB.InOrderTreeWalk(myRB.root);
		cout << endl;
	}

	RB myRB2;
	myRB2.Insert(myRB2.root, myRB2.root, 50);
	myRB2.Insert(myRB2.root, myRB2.root, 20);
	myRB2.Insert(myRB2.root, myRB2.root, 30);
	myRB2.Insert(myRB2.root, myRB2.root, 40);
	myRB2.Insert(myRB2.root, myRB2.root, 45);
	myRB2.Insert(myRB2.root, myRB2.root, 43);
	myRB2.Insert(myRB2.root, myRB2.root, 44);
	myRB2.Insert(myRB2.root, myRB2.root, 42);
	myRB2.InOrderTreeWalk(myRB2.root);
	cout << endl;
	myRB2.Delete(myRB2.root, 50);
	myRB2.InOrderTreeWalk(myRB2.root);
	cout << endl;




	//4.2 Minimal Tree : Given a sorted(increasing order) array with unique integer elements, write an
	//	algorithm to create a binary search tree with minimal height.
	int minTree[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
	TreeNode* n = MinTreeInsert(minTree, 0, 9);

	//4.5 Validate BST: Implement a function to  check if a  binary tree is a binary  search  tree.
	int* valArray = new int[10];
	CopyBST(n, valArray, 10, 0);
	for (int i = 0; i < 10; i++)
		cout << i << " ";
	cout << endl;

	cout << ValidateBST(n, -1000000)<<endl;

	//4.8 First Common Ancestor: Design an algorithm and write code to find the first common ancestor 
	// of two nodes in a binary tree.Avoid storing additional nodes in a data structure.NOTE: This is not
	//necessarily a binary search tree.

	int binaryTree[] = { 3, 5, 2, 6, 9, 7, 1, 4, 8, 10};
	TreeNode* bt = MinTreeInsert(binaryTree, 0, 9);



	//4.9 BST Sequences : A binary search tree was created by traversing through an array from left to right
	//	and inserting each element.Given a binary search tree with distinct elements, print all possible
	//	arrays that could have led to this tree.
	 

	//4.1O Check Subtree : Tl and T2 are two very large binary trees, with Tl much bigger than T2.Create an
	//	algorithm to determine ifT2 is a subtree of Tl.
	//	A tree T2 is a subtree of Tl if there exists a node n in Tl such that the subtree of n is identical to T2.
	//	That is, if you cut off the tree at node n, the two trees would be identical.


	//4.11 Random Node : You are implementing a binary search tree class from scratch, which, in addition
	//	to insert, find, and delete, has a method getRandomNode() which returns a random node
	//	from the tree.All nodes should be equally likely to be chosen.Design and implement an algorithm
	//	for getRandomNode, and explain how you would implement the rest of the methods.


	getchar();

	return 0;
}
예제 #29
0
int main() {
  AVL<int>* avl = new AVL<int>();

  avl->insert(4);   // 4

  avl->insert(7);   //     4
                    //        7
  
  avl->insert(6);   //     6
                    //   4   7

  avl->insert(10);  //     6
                    //   4   7
                    //         10

  avl->insert(12);  //     6
                    //   4      10
                    //        7     12

  avl->print();

  std::cout << "\n";
  avl->remove(6);

  avl->print();
  std::cout << "\n";
  avl->printInOrder();
  std::cout << "\n";
  avl->printPostOrder();

  return 0;

}
예제 #30
0
파일: new_avl.cpp 프로젝트: rtshadow/miscs
int main(){
    int T;
    scanf("%d", &T);
    
    const int size = 5 * 100000 + 2;
    
    int input[size];
    int preprocess[size];
    
    for(int t = 0; t < T; ++t){
        AVL tree;
        
        int n;
        scanf("%d", &n);
        //fgets(input, n + 2, stdin);
        for(int i = 0; i < n; ++i){
            scanf("%d", &input[i]);
        }
        
        preprocess[n - 1] = 1; // preprocessing z prawa na lewo
        int last = input[n - 1];
        int len = 1;
        for(int i = n - 2; i >= 0; --i){
            int current = input[i];
            if(current < last){
                preprocess[i] = ++len;
            }
            else{
                preprocess[i] = 1;
                len = 1;
            }
            last = current;
        }
        
        int max = preprocess[0];
        
        last = input[0];
        len = 1;
        tree.insert(last, 1);
        for(int i = 1; i < n; ++i){
            int current = input[i];
            if(current > last){
                ++len;
            }
            else{
                len = 1;
            }
            last = current;
            
            int m = tree.get_max(current - 1);
            if(m + preprocess[i] > max){
                max = m + preprocess[i];
            }
            if(m < len){
                tree.insert(current, len);
            }
        }
        
        printf("%d\n", max);
    }
    
    return 0;
}