Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Copyright (c) <''2010''> <''Luis E Vargas''>
- This software is provided 'as-is', without any express or implied
- warranty. In no event will the authors be held liable for any damages
- arising from the use of this software.
- Permission is granted to anyone to use this software for any purpose,
- including commercial applications, and to alter it and redistribute it
- freely, subject to the following restrictions:
- 1. The origin of this software must not be misrepresented; you must not
- claim that you wrote the original software. If you use this software
- in a product, an acknowledgment in the product documentation would be
- appreciated but is not required.
- 2. Altered source versions must be plainly marked as such, and must not be
- misrepresented as being the original software.
- 3. This notice may not be removed or altered from any source distribution.
- */
- template<typename T>
- struct arbolAVL{
- struct nodo{
- T clave;
- int altura;
- nodo *izq, *der;
- };
- nodo Dato[2000000];
- int nodos;
- arbolAVL(){
- nodos=0;
- }
- nodo* nuevo_nodo(T &clave){
- Dato[nodos].clave=clave;
- Dato[nodos].izq=NULL;
- Dato[nodos].der=NULL;
- Dato[nodos].altura=1;
- nodos++;
- return &Dato[nodos-1];
- }
- int actualiza_altura(nodo *a){
- int hizq=0, hder=0;
- if(a->izq!=NULL)
- hizq=a->izq->altura;
- if(a->der!=NULL)
- hder=a->der->altura;
- a->altura=max(hizq, hder)+1;
- }
- void rota_izq(nodo *x, nodo** padre=NULL){
- nodo *y, *a, *b, *c;
- int h=x->altura;
- assert(x->der!=NULL);
- assert(padre==NULL || *padre==x);
- y=x->der;
- a=x->izq;
- b=y->izq;
- c=y->der;
- y->izq=x;
- y->der=c;
- x->izq=a;
- x->der=b;
- if(padre!=NULL)
- *padre=y;
- actualiza_altura(x);
- actualiza_altura(y);
- }
- void rota_der(nodo *y, nodo** padre=NULL){
- nodo *x, *a, *b, *c;
- assert(y->izq!=NULL);
- assert(padre==NULL || *padre==y);
- x=y->izq;
- a=x->izq;
- b=x->der;
- c=y->der;
- x->izq=a;
- x->der=y;
- y->izq=b;
- y->der=c;
- if(padre!=NULL)
- *padre=x;
- actualiza_altura(y);
- actualiza_altura(x);
- }
- void inserta(nodo *a, T &clave, nodo** padre=NULL){
- if(clave<a->clave){
- if(a->izq==NULL){
- a->izq=nuevo_nodo(clave);
- }else{
- inserta(a->izq, clave, &a->izq);
- }
- }else{
- if(a->der==NULL){
- a->der=nuevo_nodo(clave);
- }else{
- inserta(a->der, clave, &a->der);
- }
- }
- int hizq=0, hder=0;
- if(a->izq!=NULL)
- hizq=a->izq->altura;
- if(a->der!=NULL)
- hder=a->der->altura;
- if(hizq-hder>1){
- rota_der(a, padre);
- }else if(hder-hizq>1){
- rota_izq(a, padre);
- }else{
- actualiza_altura(a);
- }
- }
- void orden(nodo *a, vector<T> &sal){
- if(a->izq!=NULL){
- orden(a->izq, sal);
- }
- sal.push_back(a->clave);
- if(a->der!=NULL){
- orden(a->der, sal);
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment