56
UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE INGENIERÍA DE SISTEMAS TEMA: IMPLEMENTACIÓN DE UN TDA, PARA ÁRBOLES BINARIOS AVL Y APLICACIÓN EN UN CASO PRÁCTICO DE GESTIÓN DE EMPLEADOS TRABAJO PRÁCTICO DEL EXAMEN COMPLEXIVO PREVIO A LA OBTENCIÓN DEL TÍTULO DE INGENIERO DE SISTEMAS AUTOR: SALAZAR AGUILAR GERONIMO ISRAEL MACHALA - EL ORO

UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

UNIDAD ACADÉMICA DE INGENIERÍA CIVIL

CARRERA DE INGENIERÍA DE SISTEMAS

TEMA:

IMPLEMENTACIÓN DE UN TDA, PARA ÁRBOLES BINARIOS AVL Y APLICACIÓN EN UN CASO PRÁCTICO DE GESTIÓN DE EMPLEADOS

TRABAJO PRÁCTICO DEL EXAMEN COMPLEXIVO PREVIO A LA OBTENCIÓN DEL TÍTULO DE INGENIERO DE SISTEMAS

AUTOR:

SALAZAR AGUILAR GERONIMO ISRAEL

MACHALA - EL ORO

Page 2: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

ii

CESIÓN DE DERECHOS DE AUTOR

Yo, SALAZAR AGUILAR GERONIMO ISRAEL, con C.I. 0705402428, estudiante de la carrera de INGENIERÍA DE SISTEMAS de la UNIDAD ACADÉMICA DE INGENIERÍA CIVIL de la UNIVERSIDAD TÉCNICA DE MACHALA, en calidad de Autor del siguiente trabajo de titulación IMPLEMENTACIÓN DE UN TDA, PARA ÁRBOLES BINARIOS AVL Y APLICACIÓN EN UN CASO PRÁCTICO DE GESTIÓN DE EMPLEADOS

• Declaro bajo juramento que el trabajo aquí descrito es de mi autoría; que no ha sido previamente presentado para ningún grado o calificación profesional. En consecuencia, asumo la responsabilidad de la originalidad del mismo y el cuidado al remitirme a las fuentes bibliográficas respectivas para fundamentar el contenido expuesto, asumiendo la responsabilidad frente a cualquier reclamo o demanda por parte de terceros de manera EXCLUSIVA.

• Cedo a la UNIVERSIDAD TÉCNICA DE MACHALA de forma NO EXCLUSIVA con referencia a la obra en formato digital los derechos de:

a. Incorporar la mencionada obra al repositorio digital institucional para su democratización a nivel mundial, respetando lo establecido por la Licencia Creative Commons Atribución-NoComercial-CompartirIgual 4.0 Internacional (CC BY-NC-SA 4.0), la Ley de Propiedad Intelectual del Estado Ecuatoriano y el Reglamento Institucional.

b. Adecuarla a cualquier formato o tecnología de uso en internet, así como incorporar cualquier sistema de seguridad para documentos electrónicos, correspondiéndome como Autor(a) la responsabilidad de velar por dichas adaptaciones con la finalidad de que no se desnaturalice el contenido o sentido de la misma.

Machala, 23 de noviembre de 2015

SALAZAR AGUILAR GERONIMO ISRAEL C.I. 0705402428

Page 3: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

iii

IMPLEMENTACIÓN DE UN TDA PARA ÁRBOLES BINARIOS AVL Y

APLICACIÓN EN UN CASO PRÁCTICO DE GESTIÓN EMPLEADOS

Geronimo Israel Salazar Aguilar

RESUMEN

La implementación de un TDA (tipo de dato abstracto) permite agrupar diferentes

tipos de datos y métodos en un solo objeto, en este caso se utiliza para crear

estructura de datos de árboles binarios AVL, empleando el lenguaje de

programación a objetos Java. La forma de crear los arboles binarios AVL en este

lenguaje es mediante una clase que contendrá las variables de tipo primitivo y

las que se utilizan para enlazarse con los nodos del subárbol izquierdo y derecho,

un constructor que inicializara el factor de equilibrio en cero y los métodos

recursivos para insertar, eliminar, modificar, buscar y las rotaciones simples y

dobles necesarias para mantener un árbol binario AVL balanceado. La utilización

de árboles binarios AVL tiene como finalidad reducir el tiempo de búsqueda de

la información de los empleados y conservarla actualizada. La información

concerniente a los empleados se guardara en 3 archivos de texto, clasificándolos

de acuerdo al departamento que pertenezcan y los intercambios que se realicen

entre departamentos se registrara temporalmente en otro archivo de texto

denominado laboral.txt. Cuando se inserta o elimina un nodo del subárbol

derecho o izquierdo debe comprobarse el factor de equilibrio del árbol para

constatar que se encuentre balanceado, en caso de no ser así se aplicaran las

rotaciones simples o dobles según sea el caso para mantenerlo balanceado.

Palabras clave

TDA, NODO, BALANCEADO, JAVA, ARCHIVO

Page 4: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

iv

TDA TO IMPLEMENTING A binary trees AVL AND APPLICATION IN CASE

MANAGEMENT EMPLOYEES

Geronimo Israel Salazar Aguilar

ABSTRACT

The implementation of an TDA (abstract data type) allows you to group different

types of data and methods in an object, in this case it is used to create data

structure of binary trees AVL using the Java programming language objects. The

way to create the binary tree in this language is AVL by a class containing

primitive variables and used to bind to nodes in the left and right subtree, a

constructor that will initialize the balance factor to zero and recursive methods to

insert, delete, modify, search and single and double rotations needed to maintain

a balanced binary tree AVL. The use of binary trees AVL aims to reduce the time

spent searching for information and keep employees updated. Information

concerning employees be saved in 3 text files, classifying them according to the

department they belong and exchanges that take place between departments is

temporarily recorded in another text file named laboral.txt. When you insert or

remove a node from the left or right subtree must be checked balancing factor to

ascertain tree that is balanced, if not so simple or double rotations are applied as

appropriate to keep it balanced.

Keywords

TDA, NODE, balanced, JAVA, FILE

Page 5: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

v

ÍNDICE DE CONTENIDOS

pág.

PORTADA …………………….……………………………………………..………..i

CESIÓN DE DERECHOS DE AUTOR……………………………………………...ii

RESUMEN ........................................................................................................ iii

ABSTRACT ....................................................................................................... iv

ÍNDICE DE CONTENIDOS ............................................................................... iv

ÍNDICE DE TABLAS ........................................................................................ vii

ÍNDICE DE FIGURAS ...................................................................................... vii

1. INTRODUCCIÓN .....................................................................................1

1.1. MARCO CONTEXTUAL ...........................................................................2

1.2. PROBLEMA .............................................................................................2

1.3. OBJETIVO GENERAL .............................................................................2

2. DESARROLLO .........................................................................................3

2.1 MARCO TEÓRICO...................................................................................3

2.1.1. Clase. .......................................................................................................3

2.1.2. TDA (tipo de dato abstracto). ...................................................................3

2.1.3 Arboles binarios equilibrado. ....................................................................3

2.1.4 Lectura de archivos en java......................................................................4

2.1.5 Recursividad ............................................................................................4

2.1.6. Java .........................................................................................................4

2.2 MARCO METODOLÓGICO .....................................................................5

2.2.1 Clase Archivo ...........................................................................................5

2.2.2 Clase NodoAVL ........................................................................................5

2.2.3 Clase ListaNodoAVL ................................................................................6

2.2.4. Diagrama de clases................................................................................15

2.3 RESULTADOS .......................................................................................16

Page 6: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

vi

3. CONCLUSIONES ...................................................................................19

4. REFERENCIAS BIBLIOGRÁFICAS ........................................................20

5. ANEXOS .................................................................................................21

Anexo 1. Rotaciones ..............................................................................21

Anexo 2. Codigo de Fuente………………………………………………….23

Anexo 3. Caso de Investigación .............................................................49

Page 7: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

vii

ÍNDICE DE TABLAS

pág.

Tabla 1: Descripción de la Figura 4: Gestión de Empleados ............................16

Tabla 2. Descripción de la Figura 5. Gestión de Empleados ............................17

Tabla 3. Descripción de la Figura 6. Gestión de Reestructuración ...................17

ÍNDICE DE FIGURAS

pág.

Figura 1. Árbol equilibrado .................................................................................3

Figura 2. Árbol binario con factor de equilibrio ...................................................4

Figura 3. Diagrama de clases ..........................................................................15

Figura 4. Gestión de Empleados ......................................................................16

Figura 5. Gestión de Empleados ......................................................................17

Figura 6. Gestión de Reestructuración .............................................................18

Figura 7. Rotación simple a la izquierda ...........................................................21

Figura 8. Rotación simple a la derecha ...........................................................21

Figura 9. Rotación doble a la izquierda ............................................................22

Figura 10. Rotación doble a la derecha ............................................................22

Page 8: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

1

1. INTRODUCCIÓN

El presente trabajo tiene como objetivo implementar un software que utilice un

TDA y archivos para guardar la información, el lenguaje de programación

seleccionado es Java, para emplear un TDA se necesita una clase que

encapsula las variables y los métodos necesarios para crear una estructura de

datos de aboles binarios AVL, estas estructura de datos se diferencia de los

arboles binarios de búsqueda comunes porque cada vez que inserta o elimina

un nodo en el árbol este comprueba su factor de equilibrio para determinar si el

árbol esta balanceado, un árbol binario AVL se encuentra balanceado si las

alturas de los subárboles izquierdos y derechos de cualquier nodo no difieren

como máximo en 1.

En caso de no estar balanceado el árbol se deben aplicar rotaciones simples o

dobles entre los nodos del árbol (ver Figura 1 y 2) para volverlo a balancearlo. El

software utiliza 3 archivos de texto para la registrar la información de los

empleados uno por cada departamento de la empresa y un archivo adicional

denominado laboral para realizar cambios de departamento de un empleado. El

proceso de cambio de departamento está compuesto de tres etapas primero

registrar la solicitud de cambio de departamento en el archivo laboral y segundo

efectúa los cambios con árboles binarios AVL y tercero eliminar las solicitudes

de cambio del archivo laboral, este proceso permite realizar varios cambios a la

vez.

Page 9: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

2

1.1. MARCO CONTEXTUAL

La empresa ALCOCI SA necesita registrar información de sus empleados y

mantenerla actualizada, por tal motivo se implementara un software desarrollado

en Java que trabaja con árboles binarios AVL y archivos de texto para almacenar

la información. El software antes de guardar un nuevo registro comprueba si los

archivos de texto existen, si este es el caso sigue agregando información en los

archivos, en caso no estar creados los archivos el software los crea y agrega la

información, para modificar el departamento en el que se encuentra un

empleado, primero se registra el cambio en un archivo de texto denominado

laboral luego con la ayuda de los arboles binarios AVL se efectúa el cambio del

departamento y por último se elimina los registros del archivo laboral.

1.2. PROBLEMA

La aplicación de TDA para estructuras de datos de árboles binarios AVL en Java

de manera eficiente implica crear una clase que contenga las variables para

enlazar los nodos del subárbol derecho e izquierdo, la raíz, un constructor, y

métodos recursivos para insertar, eliminar, rotaciones simples y dobles, buscar

y recorrer los nodos del árbol sin perder los enlaces. Los métodos de insertar y

eliminar tienen que verificar si el árbol esta balanceado, en caso no estarlo deben

aplicar las rotaciones simples o dobles a la derecha o izquierda para volver a

balancearlo, de esta manera el árbol binario AVL conserva su principal

particularidad las alturas de los subárboles izquierdos y derechos de cualquier

nodo no difieren como máximo en 1.

1.3. OBJETIVO GENERAL

Implementar un tipo de dato abstracto, utilizando el lenguaje de programación

orientado a objetos Java para crear estructuras de datos de árboles binarios

AVL

Page 10: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

3

2. DESARROLLO

2.1 MARCO TEÓRICO

2.1.1. Clase. son plantillas que están compuestas por un nombre atributos y

métodos.

2.1.2. TDA (tipo de dato abstracto). es un tipo de dato que a su vez contiene

una colección de datos y métodos que son representados en Java por una clase.

2.1.3 Arboles binarios equilibrado. Un árbol equilibrado o árbol AVL es un

árbol binario de búsqueda en el que las alturas de los subárboles izquierdo y

derecho de cualquier nodo no difieren como máximo en 1.

La altura o profundidad de un árbol binario es el nivel máximo de sus hojas más

uno. La altura de un árbol nulo se considera cero. (Joyanes Aguilar & Zahonero

Matinéz, Estructuras de datos en Java, 2007)

8

118Fe = 0

5

74

Figura 1. Árbol equilibrado Elaboración: Propia del autor

Para determinar su un árbol binario está equilibrado o no, se debe mantener

información relativa en cada nodo del árbol, esta información recibe el nombre

de factor de equilibrio está definido por al siguiente formula:

𝐅𝐞 = 𝐀𝐒𝐃 − 𝐀𝐒𝐈

Donde:

Fe: factor de equilibrio

ASD: altura del subárbol derecho

ASI: altura del subárbol izquierdo

Page 11: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

4

8Fe = -1

11Fe = 0

8Fe = 0

5Fe = 0

7Fe = 0

4Fe = 0

Figura 2. Árbol binario con factor de equilibrio Elaboración: Propia del autor

2.1.4 Lectura de archivos en java. Java no realiza operaciones directamente

con el contenido de los archivos de texto, primero debe almacenarse en un buffer

intermedio para trabajar con el contenido, con esto aumenta la eficiencia de las

operaciones.

La clase BufferedReader permite almacenar el contenido del archivo en el buffer,

además esta clase hereda métodos de la clase Reader necesarios para trabajar

con el buffer, como son readLine() y close().

2.1.5 Recursividad. la recursividad o recursión es la propiedad de un método

por la cual puede llamarse a sí mismo, en muchas circunstancias el uso de la

recursión permite a los programadores especificar soluciones naturales y

sencillas que en caso contrario serían difíciles de resolver; por esta causa la

recursión es una herramienta poderosa e importante en resolución de

problemas y en programación. (Joyanes Aguilar & Zahonero Martínez,

Programación en JAVA 6, 2011)

2.1.6. Java es un lenguaje de programación sencillo, orientado a objetos,

distribuido, interpretado, robusto, seguro, neutro ante la arquitectura, portable,

altas prestaciones, multihilo y dinámico. (Joyanes Aguilar & Zahonero Matinéz,

Estructuras de datos en Java, 2007)

Page 12: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

5

2.2 MARCO METODOLÓGICO

2.2.1 Clase Archivo. Esta clase es un ejemplo de un tda en java, un dato que

contiene una colección de datos.

package arbolavl; /** @author ISRAEL*/ public class Archivo { private int identificador; private String cedula; private String fechaNacimiento; private int departamento; private int sexo; private String lugar; private String nombre; private String apellido; private String direccion; private String correo; private String contacto; }

2.2.2 Clase NodoAVL. Esta clase implementa una variable tipo Archivo.

package arbolavl; /**@author ISRAEL */ public class NodoAVL { private Archivo archivo; private int fe; NodoAVL izdo, dcho; public NodoAVL(Archivo archivo) { this.archivo=archivo; this.fe = 0; this.izdo = dcho = null; } public NodoAVL(Archivo archivo, int vfe) { this.archivo=archivo; this.fe = vfe; this.izdo = dcho = null; } public NodoAVL(NodoAVL ramaIzdo, Archivo archivo, NodoAVL ramaDcho) { this.archivo=archivo;

Page 13: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

6

this.izdo = ramaIzdo; this.dcho = ramaDcho; this.fe = 0; } public NodoAVL(NodoAVL ramaIzdo, int vfe, Archivo archivo, NodoAVL ramaDcho) { this.archivo=archivo; this.izdo = ramaIzdo; this.dcho = ramaDcho; this.fe = vfe; } }

2.2.3 Clase ListaNodoAVL. Esta clase implementa los métodos para gestionar

los arboles binarios AVL

package arbolavl; public class ListaNodoAVL { private NodoAVL raiz; public ListaNodoAVL() { } public ListaNodoAVL(NodoAVL r) { raiz = r; } public NodoAVL getRaiz() { return raiz; } public void setRaiz(NodoAVL raiz) { this.raiz = raiz; } //ROTACIONES SIMPLES //rotación simple a la izquierda public NodoAVL rotacionII(NodoAVL n, NodoAVL n1) { n.setIzdo(n1.getDcho()); n1.setDcho(n); //actualizar factor de equilibrio if (n1.getFe() == -1) { n.setFe(0); n1.setFe(0); } else { n.setFe(-1); n1.setFe(1); } return n1; }

Page 14: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

7

//rotación simple a la derecha public NodoAVL rotacionDD(NodoAVL n, NodoAVL n1) { n.setDcho(n1.getIzdo()); n1.setIzdo(n); //actualizar factor de equilibrio if (n1.getFe() == +1) { n.setFe(0); n1.setFe(0); } else { n.setFe(+1); n1.setFe(-1); } return n1; } //ROTACIONES DOBLES //rotación doble a la izquierda public NodoAVL rotacionDI(NodoAVL n, NodoAVL n1) { NodoAVL n2; n2 = n1.getIzdo(); n.setDcho(n2.getIzdo()); n2.setIzdo(n); n1.setIzdo(n2.getDcho()); n2.setDcho(n1); //actualización factor de equilibrio if (n2.getFe() == +1) { n.setFe(-1); } else { n.setFe(0); } if (n2.getFe() == -1) { n1.setFe(+1); } else { n1.setFe(0); } n2.setFe(0); return n2; } //rotación doble a la derecha public NodoAVL rotacionID(NodoAVL n, NodoAVL n1) { NodoAVL n2; n2 = n1.getDcho(); n.setIzdo(n2.getDcho()); n2.setDcho(n); n1.setDcho(n2.getIzdo()); n2.setIzdo(n1); //actualización factor de equilibrio if (n2.getFe() == +1) { n1.setFe(-1); } else { n1.setFe(0); }

Page 15: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

8

if (n2.getFe() == -1) { n.setFe(1); } else { n.setFe(0); } n2.setFe(0); return n2; } public void insertar(NodoAVL nuevo) { raiz = insertarAVL(raiz, nuevo, false); } public NodoAVL insertarAVL(NodoAVL raiz, NodoAVL nuevo, boolean hc) { NodoAVL n1; if (raiz == null) { raiz = nuevo; hc = true; } else if (nuevo.getArchivo().getIdentificador() < raiz.getArchivo().getIdentificador()) { NodoAVL auxIz; auxIz = insertarAVL(raiz.getIzdo(), nuevo, hc); raiz.setIzdo(auxIz); //regresando por los nodos se comprueba la altura if (hc) { // decrementa el fe por aumentar la altura de rama izquierda switch (raiz.getFe()) { case 1: { raiz.setFe(0); hc = false; break; } case 0: { raiz.setFe(-1); break; } case -1: { n1 = raiz.getIzdo(); if (n1.getFe() == -1) { raiz = rotacionII(raiz, n1); } else { raiz = rotacionID(raiz, n1); } hc = false; } } } } else if (nuevo.getArchivo().getIdentificador() > raiz.getArchivo().getIdentificador()) { NodoAVL auxDr; auxDr = insertarAVL(raiz.getDcho(), nuevo, hc); raiz.setDcho(auxDr); if (hc) { switch (raiz.getFe()) {

Page 16: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

9

case 1: { n1 = raiz.getDcho(); if (n1.getFe() == +1) { raiz = rotacionDD(raiz, n1); } else { raiz = rotacionDI(raiz, n1); } hc = false; break; } case 0: { raiz.setFe(+1); break; } case -1: { raiz.setFe(0); hc = false; } } } } else { System.out.print("no puede haber 2 registros con el mismo identificador"); } return raiz; } //REESTRUCTURA DESPUES DE ELIMINAR //Reestructura Izquierda public NodoAVL reestructuraIzquierda(NodoAVL nodo, int altura) { NodoAVL auxNodo; if (altura > 0) { switch (nodo.getFe()) { case -1: { nodo.setFe(0); break; } case 0: { nodo.setFe(1); altura = 0; break; } case 1: { auxNodo = nodo.getDcho(); if (auxNodo.getFe() >= 0) {//Rotacion simple a la derecha nodo.setDcho(auxNodo.getIzdo()); auxNodo.setIzdo(nodo); switch (auxNodo.getFe()) { case 0: { nodo.setFe(1); auxNodo.setFe(-1); altura = 0; break; }

Page 17: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

10

case 1: { nodo.setFe(0); auxNodo.setFe(0); break; } } nodo = auxNodo; } else { nodo = rotacionDI(nodo, auxNodo); nodo.setFe(0); } break; } } } return nodo; } //Reestructura derecha public NodoAVL reestructuraDerecha(NodoAVL nodo, int altura) { NodoAVL auxNodo; if (altura > 0) { switch (nodo.getFe()) { case 1: { nodo.setFe(0); break; } case 0: { nodo.setFe(-1); altura = 0; break; } case -1: { auxNodo = nodo.getDcho(); if (auxNodo.getFe() <= 0) {//Rotacion simple a la izquierda nodo.setIzdo(auxNodo.getDcho()); auxNodo.setDcho(nodo); switch (auxNodo.getFe()) { case 0: { nodo.setFe(-1); auxNodo.setFe(1); altura = 0; break; } case -1: { nodo.setFe(0); auxNodo.setFe(0); break; } } nodo = auxNodo; } else { nodo = rotacionID(nodo, auxNodo); nodo.setFe(0); }

Page 18: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

11

break; } } } return nodo; } //BUSCAR REEMPLAZO /*Metodo de busqueda, del nodo de reemplazo busca el nodo mayor del subárbol de la izquierda*/ public void nodoSustituye(NodoAVL nodo, NodoAVL auxNodo, int altura) { if (nodo.getDcho() != null) { nodoSustituye(nodo.getDcho(), auxNodo, altura); if (auxNodo.getIzdo() == null) { nodo.setDcho(null); } else { nodo.setDcho(auxNodo.getIzdo()); nodo = reestructuraDerecha(nodo, altura); } } else { //Pasar valores auxNodo.setArchivo(nodo.getArchivo()); nodo = nodo.getIzdo(); altura = 1; } auxNodo.setIzdo(nodo); } //Parametros Raiz,null,0,identificador //ELIMINAR NODO public void eliminarAVL(NodoAVL nodo1, NodoAVL nodo2, int altura, int identificador) { NodoAVL auxNodo; int flag = 0; if (nodo1 != null) { if (identificador < nodo1.getArchivo().getIdentificador()) { if (altura > 0) { flag = 1; } else { if (altura != 0) { flag = -1; } altura = -1; eliminarAVL(nodo1.getIzdo(), nodo2, altura, identificador); nodo1 = reestructuraIzquierda(nodo2, altura); if (nodo2 != null) { switch (flag) { case -1: { nodo2.setIzdo(nodo1); break; } case 1: { nodo2.setDcho(nodo1); break; }

Page 19: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

12

default: { break; } } } else { raiz = nodo1; } } } else { if (identificador > nodo1.getArchivo().getIdentificador()) { if (altura < 0) { flag = -1; } else { if (altura != 0) { flag = 1; } altura = 1; eliminarAVL(nodo1.getDcho(), nodo2, altura, identificador); nodo1 = reestructuraDerecha(nodo1, altura); if (nodo2 != null) { switch (flag) { case -1: { nodo2.setIzdo(nodo1); break; } case 1: { nodo2.setDcho(nodo1); break; } default: { break; } } } else { raiz = nodo1; } } } else { nodo2 = nodo1; if (nodo2.getDcho() == null) { nodo1 = nodo2.getIzdo(); if (altura != 0) { if (altura < 0) { nodo2.setIzdo(nodo1); } else { nodo2.setDcho(nodo1); } } else { if (nodo1 == null) { raiz = null; } else { raiz = nodo1; } altura = 1; }

Page 20: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

13

} else { if (nodo2.getIzdo() == null) { nodo1 = nodo2.getDcho(); if (altura != 0) { if (altura <= 0) { nodo2.setIzdo(nodo1); } else { nodo2.setDcho(nodo1); } } else { if (nodo1 == null) { raiz = null; } else { raiz = nodo1; } } altura = 1; } else { nodoSustituye(nodo2.getIzdo(), nodo2, altura); nodo1 = reestructuraIzquierda(nodo1, altura); if (nodo2 != null) { if (altura <= 0) { nodo2.setIzdo(nodo1); } else { nodo2.setDcho(nodo1); } } else { raiz = nodo1; } } } } } } else { System.out.print("NO SE HA ENCONTRADO EL NODO"); } } //BUSCAR public NodoAVL buscar(int identificador, NodoAVL r) { if (raiz == null) { return null; } else if (r.getArchivo().getIdentificador() == identificador) { return r; } else if (r.getArchivo().getIdentificador() < identificador) { return buscar(identificador, r.getDcho()); } else { return buscar(identificador, r.getIzdo()); } } //METODOS PARA VISUALIZAR //Metodo para recorrer en arbol InOrden public String inOrden(NodoAVL r, String cadena) { if (r != null) {

Page 21: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

14

cadena = inOrden(r.getIzdo(), cadena); cadena = cadena + r.getArchivo().getIdentificador() + ";" + r.getArchivo().getDepartamento() + ";" + r.getArchivo().getCedula() + ";" + r.getArchivo().getNombre() + " " + r.getArchivo().getApellido()+"\n"; cadena = inOrden(r.getDcho(), cadena); } return cadena; } //Metodo para recorrer el arbol PreOrden public String preOrden(NodoAVL r, String cadena) { if (r != null) { cadena = cadena + r.getArchivo().getIdentificador() + ";" + r.getArchivo().getDepartamento() + ";" + r.getArchivo().getCedula() + ";" + r.getArchivo().getNombre() + " " + r.getArchivo().getApellido()+"\n"; cadena = preOrden(r.getIzdo(), cadena); cadena = preOrden(r.getDcho(), cadena); } return cadena; } //Metodo para recorrer el arbol PostOrden public String postOrden(NodoAVL r, String cadena) { if (r != null) { cadena = postOrden(r.getIzdo(), cadena); cadena = postOrden(r.getDcho(), cadena); cadena = cadena + r.getArchivo().getIdentificador() + ";" + r.getArchivo().getDepartamento() + ";" + r.getArchivo().getCedula() + ";" + r.getArchivo().getNombre() + " " + r.getArchivo().getApellido()+"\n"; } return cadena; } }

Page 22: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

15

2.2.4. Diagrama de clases

+setIdentificador()+getIdentificador()+setCedula()+getCedula()+setFechaNacimiento()+getfechaNacimiento()+setDepartamento()+getDepartamento()+setSexo()+getSexo()+setLugar()+getLugar()+setNombre()+getNombre()+setApellido()+getApellido()+setDireccion()+getDireccion()+setCorreo()+getCorreo()

-identificador : int-cedula : string-fechaNacimiento : string-departamento : int-sexo : int-lugar : string-nombre : string-apellido : string-direccion : string-correo : string-contacto : string

Archivo

+Nuevo()+Guardar()+Cancelar()+Eliminar()+Cargar Archivo()+Reestrcuturar Empleados()+dibujar()

«interface»MenuArchivo

+leerArchivo()+escribirArchivo()+borrarArchivo()+modificarRegistro()+eliminarRegistro()

ListaArchivo

1

+NodoAVL()+setFe()+getFe()+setArchivo()+getArchivo()+setIzdo()+getIzdo()+setDcho()+getDcho()

-archivo : Archivo-fe : int-izdo : NodoAVL-dcho : NodoAVL

NodoAVL

+ListaNodoAVL()+getRaiz()+rotacionII()+rotacionDD()+rotacionDI()+rotacionID()+insertarAVL()+reestructuraIzquierda()+reestructuraDerecha()+nodosustituye()+eliminarAVL()+buscar()+inOrden()+preOrden()+postOrden()

-raiz : NodoAVL

ListaNodoAVL

1

Figura 3. Diagrama de clases

Elaboración: Propia del autor

Page 23: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

16

2.3 RESULTADOS

Icono Acción Descripción

Nuevo

Habilita los cuadros de texto para insertar los varoles para un

nuevo empleado.

Edita

Habilita los cuadros de texto para cambiar los valores de los

cuadros de texto previamente debe seleccionarse el empleado.

Eliminar

Eliminar un empleado previamente debe seleccionarse el

empleado.

Cancelar Limpiar los cuadros de texto y los deshabilita

Guardar Guarda los valores de los cuadros de texto en el archivo según

el departamento seleccionado

Cargar

Registros

Carga los datos en la tabla del departamento seleccionado

Departamento Abre una ventana para modificar el departamento de un

empleado

AVL Abre una ventana para visualizar los arboles binarios AVL y

realiza el cambio de departamento de los empleados

Tabla 1: Descripción de la Figura 4: Gestión de Empleados

Elaboración: Propia del autor

Figura 4. Gestión de Empleados

Elaboración: Propia del autor

Page 24: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

17

Icono Acción Descripción

Eliminar

Elimina un registro del archivo laboral previamente debe

seleccionarse un registro

Listar Carga los registros del archivo laboral en la tabla

Tabla 2. Descripción de la Figura 5. Gestión de Empleados

Elaboración: Propia del autor

Figura 5. Gestión de Empleados

Elaboración: Propia del autor

Botón Descripción

Combo Box

Arbol

Seleccionar el árbol

Combo Box

Modo de

Visualizar

Seleccionar el modo de visualización del árbol seleccionado en

el combo box Arbol

Visualizar Carga los datos en la tabla del árbol seleccionado según el

modo de visualización

Reestructurar Realiza los cambios de los empleados que han solicitado

cambio de departamento

Tabla 3. Descripción de la Figura 6. Gestión de Reestructuración

Elaboración: Propia del autor

Page 25: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

18

Figura 6. Gestión de Reestructuración

Elaboración: Propia del autor

Page 26: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

19

3. CONCLUSIONES

El programa permitió realizar las operaciones de insertar, modificar y eliminar

empleados de los archivos de texto según el departamento al que pertenecen.

Cuando se realizan las operaciones de insertar y eliminar un nodo del árbol

binario AVL se debe comprobar el factor de equilibrio de los nodos raíz, para

determinar si el árbol esta balanceado, si el árbol está desbalanceado se deben

realizar las rotaciones simples o dobles, cuando se realizan rotaciones simples

a la izquierda o derecha el factor de equilibrio de los nodos afectados será 0, en

cambio con las rotaciones dobles se debe calcular el factor de equilibrio

aplicando la formula altura del subárbol derecho menos la altura del subárbol

izquierdo. Cuando se elimina un nodo que tiene 2 descendientes se puede

reemplazar por el nodo mayor del subárbol izquierdo o por el nodo menor del

subárbol derecho.

Page 27: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

20

4. REFERENCIAS BIBLIOGRÁFICAS

Badenas Carpio, J., Loopis Borrás, J., & Coltell Simón, Ó. (2001). CURSO

PRÁCTICO DE PROGRAMACIÓN EN C Y C++. Publidisa.

Durán, F., Gutierrez, F., & Pimentel, E. (2007). PROGRAMACIÓN ORIENTADA

A OBJETOS CON JAVA. Madrid: Thomson.

Guardati, S. (2007). ESTRUCTURA DE DATOS ORIENTADO A OBJETOS

Algoritmos con C++. Mexico: PEARSON.

JAVA. (24 de Octubre de 2015). Obtenido de

https://www.java.com/es/download/faq/whatis_java.xml

Joyanes Aguilar, L., & Zahonero Martínez, I. (2011). Programación en JAVA 6.

En L. Joyanes Aguilar, & I. Zahonero Martínez, Algoritmos y programación

a objetos (pág. 453). McGRAW-HILL.

Joyanes Aguilar, L., & Zahonero Matinéz, I. (2007). Estructuras de datos en Java.

McGraw-Hill.

Page 28: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

21

5. ANEXOS

Anexo 1. Rotaciones

Rotación simple a la izquierda

10

9

8

Fe = -2

Fe = -1

Fe = 0

9 Fe = 0

10Fe = 0

8Fe = 0

Figura 7. Rotación simple a la izquierda

Rotación simple a la derecha

10

11

12

Fe = 2

Fe = 1

Fe = 0

11 Fe = 0

12 Fe = 010 Fe = 0

Figura 8. Rotación simple a la derecha

Page 29: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

22

Rotación doble a la izquierda

10

12

11

Fe = 2

Fe = -1

Fe = 0

11Fe = 0

12Fe = 0

10Fe = 0

1. RSD

2. RSI

Figura 9. Rotación doble a la izquierda

Rotación doble a la derecha

10

12

11

Fe = -2

Fe = 1

Fe = 0

11Fe = 0

12Fe = 0

10Fe = 0

1. RSI

2. RSD

Figura 10. Rotación doble a la derecha

Page 30: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

23

Anexo 2. Código Fuente

Clases

package arbolavl;

import interfaz.*;

/** @author user */

public class Despliegue {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

// TODO code application logic here

MenuArchivo menuArchivo = new MenuArchivo();

menuArchivo.setLocationRelativeTo(null);

menuArchivo.setDefaultCloseOperation(menuArchivo.EXIT_ON_CLOSE);

menuArchivo.setVisible(true);

}

}

package arbolavl;

/** @author ISRAEL */

public class Departamento {

private String identificador;

private String departOrigen;

private String departDestino;

public Departamento() {

}

public String getIdentificador() {

return identificador;

}

public void setIdentificador(String identificador) {

this.identificador = identificador;

}

public String getDepartOrigen() {

return departOrigen;

}

public void setDepartOrigen(String departOrigen) {

this.departOrigen = departOrigen;

}

public String getDepartDestino() {

return departDestino;

}

public void setDepartDestino(String departDestino) {

this.departDestino = departDestino;

}

}

ackage arbolavl;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.OutputStreamWriter;

import java.util.ArrayList;

/**

* @author user

*/

public class ListaArchivo {

Page 31: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

24

public int contarRegistro(File archivo) {

int contador = 0;

String tmp;

try {

if (archivo.exists()) {

/*Abre un flujo de lectura a el fichero*/

BufferedReader auxArchivo = new BufferedReader(new FileReader(archivo));

while ((tmp = auxArchivo.readLine()) != null) {

String[] linea = tmp.split(";");

//Agregar cada lina a la clase arbol

contador = Integer.parseInt(linea[0]);

}

auxArchivo.close();

} else {

System.out.println("Fichero No Existe");

}

} catch (Exception e) {

/*Captura un posible error y le imprime en pantalla*/

System.out.println(e.getMessage());

contador = -1;

}

if (contador == 0) {

if (archivo.getName().equals("comercial")) {

contador=10000;

} else if (archivo.getName().equals("explotacion")) {

contador=20000;

} else {

contador=30000;

}

}

return contador;

}

public Archivo buscarRegistro(File archivo, String identificador) {

Archivo arch = new Archivo();

String tmp;

try {

if (archivo.exists()) {

/*Abre un flujo de lectura a el fichero*/

BufferedReader auxArchivo = new BufferedReader(new FileReader(archivo));

while ((tmp = auxArchivo.readLine()) != null) {

String[] linea = tmp.split(";");

//Agregar cada lina a la clase arbol

if (linea[0].equals(identificador)) {

arch.setIdentificador(Integer.parseInt(linea[0]));

arch.setCedula(linea[1]);

arch.setFechaNacimiento(linea[2]);

arch.setDepartamento(Integer.parseInt(linea[3]));

arch.setSexo(Integer.parseInt(linea[4]));

arch.setLugar(linea[5]);

arch.setNombre(linea[6]);

arch.setApellido(linea[7]);

arch.setDireccion(linea[8]);

arch.setCorreo(linea[9]);

arch.setContacto(linea[10]);

return arch;

} else {

}

}

auxArchivo.close();

} else {

System.out.println("Fichero No Existe");

}

} catch (Exception e) {

/*Captura un posible error y le imprime en pantalla*/

System.out.println(e.getMessage());

return null;

}

return arch;

}

public ArrayList<Archivo> leerArchivo(File archivo) {

ArrayList<Archivo> archivos = new ArrayList<>();

String tmp;

try {

Page 32: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

25

if (archivo.exists()) {

/*Abre un flujo de lectura a el fichero*/

BufferedReader auxArchivo = new BufferedReader(new FileReader(archivo));

while ((tmp = auxArchivo.readLine()) != null) {

String[] linea = tmp.split(";");

Archivo arch = new Archivo();

//Agregar cada lina a la clase arbol

arch.setIdentificador(Integer.parseInt(linea[0]));

arch.setCedula(linea[1]);

arch.setFechaNacimiento(linea[2]);

arch.setDepartamento(Integer.parseInt(linea[3]));

arch.setSexo(Integer.parseInt(linea[4]));

arch.setLugar(linea[5]);

arch.setNombre(linea[6]);

arch.setApellido(linea[7]);

arch.setDireccion(linea[8]);

arch.setCorreo(linea[9]);

arch.setContacto(linea[10]);

//agregar la clase arbol al ArrayList tipo arbol

archivos.add(arch);

}

auxArchivo.close();

} else {

System.out.println("Fichero No Existe");

}

} catch (Exception e) {

/*Captura un posible error y le imprime en pantalla*/

System.out.println(e.getMessage());

archivos = null;

}

return archivos;

}

public void escribirArchivo(File archivo, String cadena) {

try {

//Si no Existe el archivo lo crea

if (!archivo.exists()) {

archivo.createNewFile();

}

/*Abre un Flujo de escritura,sobre el archivo con codificacion utf-8.

*En la sentencia "FileOutputStream(archivo,true)",

*true es por si existe el archivo seguir añadiendo texto y no borrar lo que

tenia*/

BufferedWriter auxArchivo = new BufferedWriter(new OutputStreamWriter(new

FileOutputStream(archivo, true), "utf-8"));

/*Escribe en el archivo la cadena que recibe la función.

*el string "\r\n" significa salto de linea*/

auxArchivo.write(cadena + "\r\n");

//Cierra el flujo de escritura

auxArchivo.close();

System.out.println("CORRECTO");

} catch (Exception ex) {

//Captura un posible error le imprime en pantalla

System.out.println(ex.getMessage());

}

}

public void modificarRegistro(File archivo, String lineaAntigua, String lineaNueva) {

String auxNomArchivo = archivo.getParent() + "/archivoAuxiliar.txt";

//Crea un objeto File para el archivo nuevo

File arcAuxNuevo = new File(auxNomArchivo);

try {

//Si existe el archivo inical

if (archivo.exists()) {

//Abro un flujo de lectura

BufferedReader auxLectura = new BufferedReader(new FileReader(archivo));

String linea;

//Recorro el archivo de texto linea a linea

while ((linea = auxLectura.readLine()) != null) {

//Si la linea obtenida es igual a la buscada para modificar

if (linea.toString().equals(lineaAntigua.toString())) {

//Escribo la nueva linea en vez de la que tenia

escribirArchivo(arcAuxNuevo, lineaNueva);

} else {

//Escribo la linea antigua

escribirArchivo(arcAuxNuevo, linea);

Page 33: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

26

}

}

//Cierro el flujo de lectura

auxLectura.close();

borrarArchivo(archivo);

//renombro el nuevo archivo con el nombre del archivo inicial

arcAuxNuevo.renameTo(archivo);

//Cierro el flujo de lectura

//auxLectura.close();

} else {

System.out.println("Fichero No Existe");

}

} catch (Exception ex) {

//Captura un posible error y le imprime en pantalla

System.out.println(ex.getMessage());

}

}

public void borrarArchivo(File archivo) {

try {

/*Si existe el archivo*/

if (archivo.exists()) {

//Borra el archivo

archivo.delete();

System.out.println("Archivo Borrado con Exito: " + archivo.getName());

}

} catch (Exception ex) {

/*Captura un posible error y le imprime en pantalla*/

System.out.println(ex.getMessage());

}

}

public void eliminarRegistro(File archivo, String lineaAntigua) {

String auxNomArchivo = archivo.getParent() + "/archivoAuxiliar.txt";

//Crea un objeto File para el archivo nuevo

File arcAuxNuevo = new File(auxNomArchivo);

try {

//Si existe el archivo inical

if (archivo.exists()) {

//Abro un flujo de lectura

BufferedReader auxLectura = new BufferedReader(new FileReader(archivo));

String linea;

//Recorro el archivo de texto linea a linea

System.out.print(lineaAntigua);

while ((linea = auxLectura.readLine()) != null) {

//Si la linea obtenida es igual a la buscada para modificar

if (linea.toString().equals(lineaAntigua.toString())) {

}else{

//Escribo la nueva linea en vez de la que tenia

escribirArchivo(arcAuxNuevo, linea);

}

}

//Cierro el flujo de lectura

auxLectura.close();

borrarArchivo(archivo);

//renombro el nuevo archivo con el nombre del archivo inicial

arcAuxNuevo.renameTo(archivo);

} else {

System.out.println("Fichero No Existe");

}

} catch (Exception ex) {

//Captura un posible error y le imprime en pantalla

System.out.println(ex.getMessage());

}

}

}

package arbolavl;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

Page 34: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

27

import java.io.FileReader;

import java.io.OutputStreamWriter;

import java.util.ArrayList;

/**

* @author user

*/

public class ListaDepartamento {

public ArrayList<Departamento> leerArchivo(File archivo) {

ArrayList<Departamento> archivos = new ArrayList<>();

String tmp;

try {

if (archivo.exists()) {

/*Abre un flujo de lectura a el fichero*/

BufferedReader auxArchivo = new BufferedReader(new FileReader(archivo));

while ((tmp = auxArchivo.readLine()) != null) {

String[] linea = tmp.split(";");

Departamento arch = new Departamento();

//Agregar cada lina a la clase arbol

arch.setIdentificador(linea[0]);

arch.setDepartOrigen(linea[1]);

arch.setDepartDestino(linea[2]);

//agregar la clase arbol al ArrayList tipo arbol

archivos.add(arch);

}

auxArchivo.close();

} else {

System.out.println("Fichero No Existe");

}

} catch (Exception e) {

/*Captura un posible error y le imprime en pantalla*/

System.out.println(e.getMessage());

archivos = null;

}

return archivos;

}

public void escribirArchivo(File archivo, String cadena) {

try {

//Si no Existe el archivo lo crea

if (!archivo.exists()) {

archivo.createNewFile();

}

/*Abre un Flujo de escritura,sobre el archivo con codificacion utf-8.

*En la sentencia "FileOutputStream(archivo,true)",

*true es por si existe el archivo seguir añadiendo texto y no borrar lo que

tenia*/

BufferedWriter auxArchivo = new BufferedWriter(new OutputStreamWriter(new

FileOutputStream(archivo, true), "utf-8"));

/*Escribe en el archivo la cadena que recibe la función.

*el string "\r\n" significa salto de linea*/

auxArchivo.write(cadena + "\r\n");

//Cierra el flujo de escritura

auxArchivo.close();

System.out.println("CORRECTO");

} catch (Exception ex) {

//Captura un posible error le imprime en pantalla

System.out.println(ex.getMessage());

}

}

public void borrarArchivo(File archivo) {

try {

/*Si existe el archivo*/

if (archivo.exists()) {

//Borra el archivo

archivo.delete();

System.out.println("Archivo Borrado con Exito" + archivo.getName());

}

} catch (Exception ex) {

/*Captura un posible error y le imprime en pantalla*/

System.out.println(ex.getMessage());

}

}

public void eliminarRegistro(File archivo, String lineaAntigua) {

Page 35: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

28

String auxNomArchivo = archivo.getParent() + "/laboralAuxiliar.txt";

//Crea un objeto File para el archivo nuevo

File arcAuxNuevo = new File(auxNomArchivo);

try {

//Si existe el archivo inical

if (archivo.exists()) {

//Abro un flujo de lectura

BufferedReader auxLectura = new BufferedReader(new FileReader(archivo));

String linea;

//Recorro el archivo de texto linea a linea

while ((linea = auxLectura.readLine()) != null) {

//Si la linea obtenida es igual a la buscada para modificar

if (!linea.toString().equals(lineaAntigua.toString())) {

//Escribo la nueva linea en vez de la que tenia

escribirArchivo(arcAuxNuevo, linea);

}

}

//Cierro el flujo de lectura

auxLectura.close();

borrarArchivo(archivo);

//renombro el nuevo archivo con el nombre del archivo inicial

arcAuxNuevo.renameTo(archivo);

//Cierro el flujo de lectura

//auxLectura.close();

} else {

System.out.println("Fichero No Existe");

}

} catch (Exception ex) {

//Captura un posible error y le imprime en pantalla

System.out.println(ex.getMessage());

}

}

}

Interfaces

package interfaz;

import arbolavl.*;

import java.io.File;

import java.util.ArrayList;

import javax.swing.table.DefaultTableModel;

/** @author ISRAEL */

public class MenuArbol extends javax.swing.JDialog {

File archivoLaboral = new File("D:\\laboral.txt");

File archivoComercial = new File("D:\\comercial.txt");

File archivoExplotacion = new File("D:\\explotacion.txt");

File archivoMarketing = new File("D:\\marketing.txt");

ListaNodoAVL listaNodoComercial = new ListaNodoAVL();

ListaNodoAVL listaNodoExplotacion = new ListaNodoAVL();

ListaNodoAVL listaNodoMarketing = new ListaNodoAVL();

public void dibujarTabla(String[] arreglo) {

DefaultTableModel modelo = new DefaultTableModel() {

@Override

public boolean isCellEditable(int row, int col) {

return false;

}

};

Object[] fila = new Object[4];

String[] columnas = {"Identificador", "Departamento", "Cedula", "Nombres y

Apellidos"};

modelo.setColumnIdentifiers(columnas);

try{

for (int j = 0; j < arreglo.length; j++) {

String[] auxArreglo = new String[4];

auxArreglo = arreglo[j].split(";");

fila[0] = auxArreglo[0];

fila[1] = auxArreglo[1];

Page 36: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

29

fila[2] = auxArreglo[2];

fila[3] = auxArreglo[3];

modelo.addRow(fila);

}

tb_arbol.setModel(modelo);

}catch(Exception e){

tb_arbol.setModel(modelo);

}

}

public MenuArbol(java.awt.Frame parent, boolean modal) {

super(parent, modal);

initComponents();

//arbolAVL.inOrden(arbol1);

}

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();

tb_arbol = new javax.swing.JTable();

btn_visualizar = new javax.swing.JButton();

cmb_arbol = new javax.swing.JComboBox();

jLabel1 = new javax.swing.JLabel();

jLabel2 = new javax.swing.JLabel();

cmb_modo = new javax.swing.JComboBox();

btn_reestructurar = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

setTitle("Gestión de Reestructuración");

tb_arbol.setModel(new javax.swing.table.DefaultTableModel(

new Object [][] {

{null, null, null, null},

{null, null, null, null},

{null, null, null, null},

{null, null, null, null}

},

new String [] {

"Identificador", "Departamento", "Cedula", "Nombres y Apellidos"

}

));

jScrollPane1.setViewportView(tb_arbol);

if (tb_arbol.getColumnModel().getColumnCount() > 0) {

tb_arbol.getColumnModel().getColumn(0).setPreferredWidth(5);

tb_arbol.getColumnModel().getColumn(1).setPreferredWidth(5);

tb_arbol.getColumnModel().getColumn(2).setPreferredWidth(10);

tb_arbol.getColumnModel().getColumn(3).setPreferredWidth(200);

}

btn_visualizar.setText("Visualizar");

btn_visualizar.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_visualizarActionPerformed(evt);

}

});

cmb_arbol.setModel(new javax.swing.DefaultComboBoxModel(new String[] {

"Comercial", "Explotación", "Marketing" }));

jLabel1.setText("Árbol");

jLabel2.setText("Modo de Visualizar");

cmb_modo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "InOrden",

"PreOrden", "PostOrden" }));

btn_reestructurar.setText("Reestructurar");

btn_reestructurar.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_reestructurarActionPerformed(evt);

}

});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

Page 37: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

30

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jScrollPane1)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(jLabel1)

.addGap(18, 18, 18)

.addComponent(cmb_arbol,

javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addGap(54, 54, 54)

.addComponent(jLabel2)

.addGap(29, 29, 29)

.addComponent(cmb_modo,

javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(layout.createSequentialGroup()

.addGap(239, 239, 239)

.addComponent(btn_reestructurar,

javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 173,

Short.MAX_VALUE)

.addComponent(btn_visualizar)))

.addContainerGap())

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addContainerGap()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(btn_visualizar)

.addComponent(cmb_arbol, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel1)

.addComponent(jLabel2)

.addComponent(cmb_modo, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18, 18, 18)

.addComponent(btn_reestructurar, javax.swing.GroupLayout.DEFAULT_SIZE,

50, Short.MAX_VALUE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap())

);

pack();

}// </editor-fold>

private void btn_visualizarActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

switch (cmb_arbol.getSelectedIndex()) {

case 0: {

ListaArchivo listaArchivo = new ListaArchivo();

ArrayList<Archivo> archivoC = new ArrayList<>();

archivoC = listaArchivo.leerArchivo(archivoComercial);

for (int i = 0; i < archivoC.size(); i++) {

NodoAVL nodoComercial = new NodoAVL(archivoC.get(i));

listaNodoComercial.insertar(nodoComercial);

}

if (cmb_modo.getSelectedIndex() == 0) {

String[] arreglo =

listaNodoComercial.inOrden(listaNodoComercial.getRaiz(), "").split("\\r?\\n");

dibujarTabla(arreglo);

Page 38: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

31

} else if (cmb_modo.getSelectedIndex() == 1) {

String[] arreglo =

listaNodoComercial.preOrden(listaNodoComercial.getRaiz(), "").split("\\r?\\n");

dibujarTabla(arreglo);

} else {

String[] arreglo =

listaNodoComercial.postOrden(listaNodoComercial.getRaiz(), "").split("\\r?\\n");

dibujarTabla(arreglo);

}

listaNodoComercial.setRaiz(null);

break;

}

case 1: {

ListaArchivo listaArchivo = new ListaArchivo();

ArrayList<Archivo> archivoC = new ArrayList<>();

archivoC = listaArchivo.leerArchivo(archivoExplotacion);

for (int i = 0; i < archivoC.size(); i++) {

NodoAVL nodoComercial = new NodoAVL(archivoC.get(i));

listaNodoExplotacion.insertar(nodoComercial);

}

if (cmb_modo.getSelectedIndex() == 0) {

String[] arreglo =

listaNodoComercial.inOrden(listaNodoExplotacion.getRaiz(), "").split("\\r?\\n");

dibujarTabla(arreglo);

} else if (cmb_modo.getSelectedIndex() == 1) {

String[] arreglo =

listaNodoComercial.preOrden(listaNodoExplotacion.getRaiz(), "").split("\\r?\\n");

dibujarTabla(arreglo);

} else {

String[] arreglo =

listaNodoComercial.postOrden(listaNodoExplotacion.getRaiz(), "").split("\\r?\\n");

dibujarTabla(arreglo);

}

listaNodoExplotacion.setRaiz(null);

break;

}

case 2: {

ListaArchivo listaArchivo = new ListaArchivo();

ArrayList<Archivo> archivoC = new ArrayList<>();

archivoC = listaArchivo.leerArchivo(archivoMarketing);

for (int i = 0; i < archivoC.size(); i++) {

NodoAVL nodoComercial = new NodoAVL(archivoC.get(i));

listaNodoMarketing.insertar(nodoComercial);

}

if (cmb_modo.getSelectedIndex() == 0) {

String[] arreglo =

listaNodoComercial.inOrden(listaNodoMarketing.getRaiz(), "").split("\\r?\\n");

dibujarTabla(arreglo);

} else if (cmb_modo.getSelectedIndex() == 1) {

String[] arreglo =

listaNodoComercial.preOrden(listaNodoMarketing.getRaiz(), "").split("\\r?\\n");

dibujarTabla(arreglo);

} else {

String[] arreglo =

listaNodoComercial.postOrden(listaNodoMarketing.getRaiz(), "").split("\\r?\\n");

dibujarTabla(arreglo);

}

listaNodoMarketing.setRaiz(null);

break;

}

}

}

private void btn_reestructurarActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

ListaDepartamento listaDepartamento = new ListaDepartamento();

int auxcontador = 0;

Archivo archivo = new Archivo();

String cadenaNueva, cadenaAntigua;

Page 39: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

32

ArrayList<Departamento> auxDepartamento = new ArrayList<>();

auxDepartamento = listaDepartamento.leerArchivo(archivoLaboral);

for (int i = 0; i < auxDepartamento.size(); i++) {

if (Integer.parseInt(auxDepartamento.get(i).getDepartOrigen()) == 1) {

ListaArchivo listaArchivo = new ListaArchivo();

archivo =

listaArchivo.buscarRegistro(archivoComercial,auxDepartamento.get(i).getIdentificador());

switch (Integer.parseInt(auxDepartamento.get(i).getDepartDestino())) {

case 2: {

auxcontador = listaArchivo.contarRegistro(archivoExplotacion);

cadenaNueva = (auxcontador + 1) + ";" + archivo.getCedula() + ";"

+ archivo.getFechaNacimiento() + ";" + 2 + ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

cadenaAntigua = archivo.getIdentificador() + ";" +

archivo.getCedula() + ";" + archivo.getFechaNacimiento() + ";" +

archivo.getDepartamento()+ ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

ListaArchivo lista= new ListaArchivo();

lista.eliminarRegistro(archivoComercial, cadenaAntigua);

listaArchivo.escribirArchivo(archivoExplotacion, cadenaNueva);

break;

}

case 3: {

auxcontador = listaArchivo.contarRegistro(archivoMarketing);

cadenaNueva = (auxcontador + 1) + ";" + archivo.getCedula() + ";"

+ archivo.getFechaNacimiento() + ";" + 3 + ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

cadenaAntigua = archivo.getIdentificador() + ";" +

archivo.getCedula() + ";" + archivo.getFechaNacimiento() + ";" + archivo.getDepartamento()

+ ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

ListaArchivo lista= new ListaArchivo();

lista.eliminarRegistro(archivoComercial, cadenaAntigua);

listaArchivo.escribirArchivo(archivoMarketing, cadenaNueva);

break;

}

}

} else if (Integer.parseInt(auxDepartamento.get(i).getDepartOrigen()) == 2) {

ListaArchivo listaArchivo = new ListaArchivo();

archivo = listaArchivo.buscarRegistro(archivoExplotacion,

auxDepartamento.get(i).getIdentificador());

switch (Integer.parseInt(auxDepartamento.get(i).getDepartDestino())) {

case 1: {

auxcontador = listaArchivo.contarRegistro(archivoComercial);

cadenaNueva = (auxcontador + 1) + ";" + archivo.getCedula() + ";"

+ archivo.getFechaNacimiento() + ";" + 1 + ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

Page 40: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

33

cadenaAntigua = archivo.getIdentificador() + ";" +

archivo.getCedula() + ";" + archivo.getFechaNacimiento() + ";" + archivo.getDepartamento()

+ ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

ListaArchivo lista= new ListaArchivo();

lista.eliminarRegistro(archivoExplotacion, cadenaAntigua);

listaArchivo.escribirArchivo(archivoComercial, cadenaNueva);

break;

}

case 3: {

auxcontador = listaArchivo.contarRegistro(archivoMarketing);

cadenaNueva = (auxcontador + 1) + ";" + archivo.getCedula() + ";"

+ archivo.getFechaNacimiento() + ";" + 3 + ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

cadenaAntigua = archivo.getIdentificador() + ";" +

archivo.getCedula() + ";" + archivo.getFechaNacimiento() + ";" + archivo.getDepartamento()

+ ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

ListaArchivo lista= new ListaArchivo();

lista.eliminarRegistro(archivoExplotacion, cadenaAntigua);

listaArchivo.escribirArchivo(archivoMarketing, cadenaNueva);

break;

}

}

} else {

ListaArchivo listaArchivo = new ListaArchivo();

archivo = listaArchivo.buscarRegistro(archivoMarketing,

auxDepartamento.get(i).getIdentificador());

switch (Integer.parseInt(auxDepartamento.get(i).getDepartDestino())) {

case 1: {

auxcontador = listaArchivo.contarRegistro(archivoComercial);

cadenaNueva = (auxcontador + 1) + ";" + archivo.getCedula() + ";"

+ archivo.getFechaNacimiento() + ";" + 1 + ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

cadenaAntigua = archivo.getIdentificador() + ";" +

archivo.getCedula() + ";" + archivo.getFechaNacimiento() + ";" + archivo.getDepartamento()

+ ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

ListaArchivo lista= new ListaArchivo();

lista.eliminarRegistro(archivoMarketing, cadenaAntigua);

listaArchivo.escribirArchivo(archivoComercial, cadenaNueva);

break;

}

case 2: {

auxcontador = listaArchivo.contarRegistro(archivoExplotacion);

cadenaNueva = (auxcontador + 1) + ";" + archivo.getCedula() + ";"

+ archivo.getFechaNacimiento() + ";" + 2 + ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

Page 41: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

34

cadenaAntigua = archivo.getIdentificador() + ";" +

archivo.getCedula() + ";" + archivo.getFechaNacimiento() + ";" + archivo.getDepartamento()

+ ";"

+ archivo.getSexo() + ";" + archivo.getLugar() + ";" +

archivo.getNombre() + ";" + archivo.getApellido() + ";"

+ archivo.getDireccion() + ";" + archivo.getCorreo() + ";"

+ archivo.getContacto();

ListaArchivo lista= new ListaArchivo();

lista.eliminarRegistro(archivoMarketing, cadenaAntigua);

listaArchivo.escribirArchivo(archivoExplotacion, cadenaNueva);

break;

}

}

}

}

listaDepartamento.borrarArchivo(archivoLaboral);

}

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code

(optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default

look and feel.

* For details see

http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

try {

for (javax.swing.UIManager.LookAndFeelInfo info :

javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

}

}

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(MenuArbol.class.getName()).log(java.util.logging.Leve

l.SEVERE, null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(MenuArbol.class.getName()).log(java.util.logging.Leve

l.SEVERE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(MenuArbol.class.getName()).log(java.util.logging.Leve

l.SEVERE, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(MenuArbol.class.getName()).log(java.util.logging.Leve

l.SEVERE, null, ex);

}

//</editor-fold>

/* Create and display the dialog */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

MenuArbol dialog = new MenuArbol(new javax.swing.JFrame(), true);

dialog.addWindowListener(new java.awt.event.WindowAdapter() {

@Override

public void windowClosing(java.awt.event.WindowEvent e) {

System.exit(0);

}

});

dialog.setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.JButton btn_reestructurar;

private javax.swing.JButton btn_visualizar;

private javax.swing.JComboBox cmb_arbol;

private javax.swing.JComboBox cmb_modo;

Page 42: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

35

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JTable tb_arbol;

// End of variables declaration

}

package interfaz;

import arbolavl.*;

import java.awt.Point;

import java.io.File;

import java.util.ArrayList;

import javax.swing.JOptionPane;

import javax.swing.table.*;

/**

* @author user

*/

public class MenuArchivo extends javax.swing.JFrame {

/**

* Creates new form MenuArchivo

*/

/*Creo un objeto File. Recibe como parámetro la ruta con el nombre del archivo */

File archivoLaboral = new File("D:\\laboral.txt");

File archivoComercial = new File("D:\\comercial.txt");

File archivoExplotacion = new File("D:\\explotacion.txt");

File archivoMarketing = new File("D:\\marketing.txt");

int editar = 0;

static String cadenaAntigua = null;

int auxDepart = -1;

public void dibujarTabla(ArrayList<Archivo> arreglo) {

DefaultTableModel modelo = new DefaultTableModel() {

@Override

public boolean isCellEditable(int row, int col) {

return false;

}

};

Object[] fila = new Object[5];

String[] columnas = {"Identificador", "Cedula", "Departamento", "Nombres y

Apellidos", "Contacto"};

modelo.setColumnIdentifiers(columnas);

for (int i = 0; i < arreglo.size(); i++) {

fila[0] = arreglo.get(i).getIdentificador();

fila[1] = arreglo.get(i).getCedula();

//COMPROBAR DEPARTAMENTO

if (arreglo.get(i).getDepartamento() == 1) {

fila[2] = "Comercial";

} else {

if (arreglo.get(i).getDepartamento() == 2) {

fila[2] = "Explotación";

} else {

fila[2] = "Marketing";

}

}

fila[3] = arreglo.get(i).getNombre() + " " + arreglo.get(i).getApellido();

fila[4] = arreglo.get(i).getContacto();

modelo.addRow(fila);

}

tb_tablaArchivo.setModel(modelo);

}

public void limpiar() {

editar = 0;

cadenaAntigua = null;

txt_identificador.setText(null);

txt_cedula.setText(null);

txt_fecha.setText(null);

Page 43: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

36

cmb_departamento.setSelectedIndex(0);

cmb_sexo.setSelectedIndex(0);

txt_lugar.setText(null);

txt_nombre.setText(null);

txt_apellido.setText(null);

txt_direccion.setText(null);

txt_correo.setText(null);

txt_contacto.setText(null);

cmb_departamento.setEnabled(true);

}

public MenuArchivo() {

initComponents();

}

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jPanel1 = new javax.swing.JPanel();

jScrollPane2 = new javax.swing.JScrollPane();

txt_direccion = new javax.swing.JTextArea();

btn_departamento = new javax.swing.JButton();

bt_editar = new javax.swing.JButton();

txt_lugar = new javax.swing.JTextField();

jLabel8 = new javax.swing.JLabel();

cmb_departamento = new javax.swing.JComboBox();

txt_correo = new javax.swing.JTextField();

jLabel11 = new javax.swing.JLabel();

txt_fecha = new javax.swing.JTextField();

jLabel10 = new javax.swing.JLabel();

txt_contacto = new javax.swing.JTextField();

jLabel9 = new javax.swing.JLabel();

jLabel7 = new javax.swing.JLabel();

cmb_sexo = new javax.swing.JComboBox();

jLabel6 = new javax.swing.JLabel();

txt_cedula = new javax.swing.JTextField();

jLabel3 = new javax.swing.JLabel();

txt_apellido = new javax.swing.JTextField();

jLabel2 = new javax.swing.JLabel();

jLabel5 = new javax.swing.JLabel();

btn_crearArbol = new javax.swing.JButton();

btn_eliminar = new javax.swing.JButton();

btn_cancelar = new javax.swing.JButton();

btn_guardar = new javax.swing.JButton();

txt_nombre = new javax.swing.JTextField();

txt_identificador = new javax.swing.JTextField();

jLabel4 = new javax.swing.JLabel();

jLabel1 = new javax.swing.JLabel();

btn_nuevo = new javax.swing.JButton();

jScrollPane1 = new javax.swing.JScrollPane();

tb_tablaArchivo = new javax.swing.JTable();

btn_leerArchivo = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setTitle("Gestión de Empleados");

getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

jPanel1.setLayout(null);

txt_direccion.setColumns(20);

txt_direccion.setRows(5);

txt_direccion.setEnabled(false);

jScrollPane2.setViewportView(txt_direccion);

jPanel1.add(jScrollPane2);

jScrollPane2.setBounds(170, 230, 514, 56);

btn_departamento.setText("Departamento");

btn_departamento.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_departamentoActionPerformed(evt);

}

});

jPanel1.add(btn_departamento);

btn_departamento.setBounds(491, 11, 120, 30);

Page 44: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

37

bt_editar.setIcon(new

javax.swing.ImageIcon(getClass().getResource("/iconos/iconos/document_edit.png"))); //

NOI18N

bt_editar.setEnabled(false);

bt_editar.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

bt_editarActionPerformed(evt);

}

});

jPanel1.add(bt_editar);

bt_editar.setBounds(189, 11, 59, 33);

txt_lugar.setEnabled(false);

jPanel1.add(txt_lugar);

txt_lugar.setBounds(520, 150, 100, 20);

jLabel8.setText("Lugar de Residencia:");

jPanel1.add(jLabel8);

jLabel8.setBounds(390, 150, 120, 14);

cmb_departamento.setModel(new javax.swing.DefaultComboBoxModel(new String[] {

"Comercial", "Explotación", "Marketing" }));

jPanel1.add(cmb_departamento);

cmb_departamento.setBounds(520, 110, 100, 22);

txt_correo.setEnabled(false);

jPanel1.add(txt_correo);

txt_correo.setBounds(170, 310, 193, 20);

jLabel11.setText("Correo Electronico:");

jPanel1.add(jLabel11);

jLabel11.setBounds(50, 310, 110, 14);

txt_fecha.setEnabled(false);

jPanel1.add(txt_fecha);

txt_fecha.setBounds(170, 110, 100, 20);

jLabel10.setText("Fecha de Nacimiento:");

jPanel1.add(jLabel10);

jLabel10.setBounds(30, 110, 130, 14);

txt_contacto.setEnabled(false);

jPanel1.add(txt_contacto);

txt_contacto.setBounds(520, 310, 210, 20);

jLabel9.setText("Contacto:");

jPanel1.add(jLabel9);

jLabel9.setBounds(460, 310, 60, 14);

jLabel7.setText("Dirección:");

jPanel1.add(jLabel7);

jLabel7.setBounds(100, 250, 70, 14);

cmb_sexo.setModel(new javax.swing.DefaultComboBoxModel(new String[] {

"Masculino", "Femenino" }));

cmb_sexo.setEnabled(false);

jPanel1.add(cmb_sexo);

cmb_sexo.setBounds(170, 150, 100, 22);

jLabel6.setText("Sexo:");

jPanel1.add(jLabel6);

jLabel6.setBounds(120, 150, 50, 14);

txt_cedula.setEnabled(false);

jPanel1.add(txt_cedula);

txt_cedula.setBounds(520, 65, 100, 20);

jLabel3.setText("Cedula:");

jPanel1.add(jLabel3);

jLabel3.setBounds(460, 70, 60, 14);

txt_apellido.setEnabled(false);

jPanel1.add(txt_apellido);

txt_apellido.setBounds(520, 180, 210, 20);

jLabel2.setText("Apellidos:");

jPanel1.add(jLabel2);

Page 45: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

38

jLabel2.setBounds(450, 180, 60, 14);

jLabel5.setText("Departamento:");

jPanel1.add(jLabel5);

jLabel5.setBounds(420, 110, 90, 14);

btn_crearArbol.setText("AVL");

btn_crearArbol.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_crearArbolActionPerformed(evt);

}

});

jPanel1.add(btn_crearArbol);

btn_crearArbol.setBounds(640, 10, 60, 30);

btn_eliminar.setIcon(new

javax.swing.ImageIcon(getClass().getResource("/iconos/iconos/delete.png"))); // NOI18N

btn_eliminar.setEnabled(false);

btn_eliminar.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_eliminarActionPerformed(evt);

}

});

jPanel1.add(btn_eliminar);

btn_eliminar.setBounds(414, 11, 59, 33);

btn_cancelar.setIcon(new

javax.swing.ImageIcon(getClass().getResource("/iconos/iconos/cancel.png"))); // NOI18N

btn_cancelar.setEnabled(false);

btn_cancelar.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_cancelarActionPerformed(evt);

}

});

jPanel1.add(btn_cancelar);

btn_cancelar.setBounds(339, 11, 59, 33);

btn_guardar.setIcon(new

javax.swing.ImageIcon(getClass().getResource("/iconos/iconos/save.png"))); // NOI18N

btn_guardar.setEnabled(false);

btn_guardar.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_guardarActionPerformed(evt);

}

});

jPanel1.add(btn_guardar);

btn_guardar.setBounds(264, 11, 59, 33);

txt_nombre.setEnabled(false);

jPanel1.add(txt_nombre);

txt_nombre.setBounds(170, 190, 210, 20);

txt_identificador.setEnabled(false);

jPanel1.add(txt_identificador);

txt_identificador.setBounds(170, 70, 100, 20);

txt_identificador.getAccessibleContext().setAccessibleName("");

jLabel4.setText("Nombres:");

jPanel1.add(jLabel4);

jLabel4.setBounds(100, 190, 60, 14);

jLabel1.setText("Identificador:");

jPanel1.add(jLabel1);

jLabel1.setBounds(80, 70, 80, 14);

btn_nuevo.setIcon(new

javax.swing.ImageIcon(getClass().getResource("/iconos/iconos/add.png"))); // NOI18N

btn_nuevo.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_nuevoActionPerformed(evt);

}

});

jPanel1.add(btn_nuevo);

btn_nuevo.setBounds(114, 11, 59, 33);

tb_tablaArchivo.setModel(new javax.swing.table.DefaultTableModel(

new Object [][] {

Page 46: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

39

{"", null, null, null, null},

{null, null, null, null, null},

{null, null, null, null, null},

{null, null, null, null, null}

},

new String [] {

"Identificador", "Cedula", "Departamento", "Nombres y Apellidos",

"Contacto"

}

) {

Class[] types = new Class [] {

java.lang.String.class, java.lang.Object.class, java.lang.String.class,

java.lang.String.class, java.lang.String.class

};

public Class getColumnClass(int columnIndex) {

return types [columnIndex];

}

});

tb_tablaArchivo.setToolTipText("");

tb_tablaArchivo.addMouseListener(new java.awt.event.MouseAdapter() {

public void mousePressed(java.awt.event.MouseEvent evt) {

tb_tablaArchivoMousePressed(evt);

}

});

jScrollPane1.setViewportView(tb_tablaArchivo);

tb_tablaArchivo.getAccessibleContext().setAccessibleName("tb_tablaArchivo");

jPanel1.add(jScrollPane1);

jScrollPane1.setBounds(0, 350, 874, 180);

btn_leerArchivo.setText("Cargar Registros");

btn_leerArchivo.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_leerArchivoActionPerformed(evt);

}

});

jPanel1.add(btn_leerArchivo);

btn_leerArchivo.setBounds(640, 110, 140, 23);

btn_leerArchivo.getAccessibleContext().setAccessibleName("btn_leerArchivo");

getContentPane().add(jPanel1, new

org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 880, 536));

pack();

}// </editor-fold>

private void btn_leerArchivoActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

ListaArchivo listaArchivo = new ListaArchivo();

// System.out.println(listaArchivo.leerArchivo().get().getNombre());

try {

switch (cmb_departamento.getSelectedIndex()) {

case 0: {

dibujarTabla(listaArchivo.leerArchivo(archivoComercial));

break;

}

case 1: {

dibujarTabla(listaArchivo.leerArchivo(archivoExplotacion));

break;

}

case 2: {

dibujarTabla(listaArchivo.leerArchivo(archivoMarketing));

break;

}

}

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Se Produjo al cargar el archivo...");

}

}

private void btn_nuevoActionPerformed(java.awt.event.ActionEvent evt) {

limpiar();

activarCajas(true);

txt_identificador.setEnabled(true);

activarBotones(true);

Page 47: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

40

bt_editar.setEnabled(false);

btn_guardar.setEnabled(true);

btn_eliminar.setEnabled(false);

btn_cancelar.setEnabled(true);

}

private void btn_guardarActionPerformed(java.awt.event.ActionEvent evt) {

String cadenaNueva = null;

ListaArchivo listaArchivo = new ListaArchivo();

if (txt_identificador.getText().length() != 0) {

if (editar == 0) {

cadenaNueva = txt_identificador.getText() + ";" + txt_cedula.getText() +

";" + txt_fecha.getText() + ";"

+ (cmb_departamento.getSelectedIndex() + 1) + ";" +

(cmb_sexo.getSelectedIndex() + 1) + ";" + txt_lugar.getText() + ";"

+ txt_nombre.getText() + ";" + txt_apellido.getText() + ";" +

txt_direccion.getText() + ";" + txt_correo.getText() + ";"

+ txt_contacto.getText();

switch (cmb_departamento.getSelectedIndex()) {

case 0: {

listaArchivo.escribirArchivo(archivoComercial, cadenaNueva);

break;

}

case 1: {

listaArchivo.escribirArchivo(archivoExplotacion, cadenaNueva);

break;

}

case 2: {

listaArchivo.escribirArchivo(archivoMarketing, cadenaNueva);

break;

}

}

} else {

if (auxDepart == (cmb_departamento.getSelectedIndex() + 1)) {

cadenaNueva = txt_identificador.getText() + ";" + txt_cedula.getText()

+ ";" + txt_fecha.getText() + ";"

+ (cmb_departamento.getSelectedIndex() + 1) + ";" +

(cmb_sexo.getSelectedIndex() + 1) + ";" + txt_lugar.getText() + ";"

+ txt_nombre.getText() + ";" + txt_apellido.getText() + ";" +

txt_direccion.getText() + ";" + txt_correo.getText() + ";"

+ txt_contacto.getText();

} else {

cadenaNueva = txt_identificador.getText() + ";" + txt_cedula.getText()

+ ";" + txt_fecha.getText() + ";"

+ auxDepart + ";" + (cmb_sexo.getSelectedIndex() + 1) + ";" +

txt_lugar.getText() + ";"

+ txt_nombre.getText() + ";" + txt_apellido.getText() + ";" +

txt_direccion.getText() + ";" + txt_correo.getText() + ";"

+ txt_contacto.getText();

String cadena = txt_identificador.getText() + ";" + auxDepart + ";" +

((cmb_departamento.getSelectedIndex() + 1));

listaArchivo.escribirArchivo(archivoLaboral, cadena);

}

switch (auxDepart - 1) {

case 0: {

listaArchivo.modificarRegistro(archivoComercial, cadenaAntigua,

cadenaNueva);

break;

}

case 1: {

listaArchivo.modificarRegistro(archivoExplotacion,

cadenaAntigua, cadenaNueva);

break;

}

case 2: {

listaArchivo.modificarRegistro(archivoMarketing, cadenaAntigua,

cadenaNueva);

break;

}

}

}

limpiar();

activarCajas(false);

Page 48: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

41

txt_identificador.setEnabled(false);

activarBotones(false);

btn_guardar.setEnabled(false);

cadenaAntigua=null;

} else {

JOptionPane.showMessageDialog(null, "Verificar los datos");

}

editar = 0;

auxDepart = -1;

limpiar();

}

private void btn_cancelarActionPerformed(java.awt.event.ActionEvent evt) {

limpiar();

activarBotones(false);

txt_identificador.setEnabled(false);

btn_guardar.setEnabled(false);

activarCajas(false);

cadenaAntigua=null;

}

private void tb_tablaArchivoMousePressed(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

editar = 1;

auxDepart = cmb_departamento.getSelectedIndex() + 1;

Point puntoFC;

int indiceFila = 0;

try {

if (evt.getClickCount() == 2) {

puntoFC = evt.getPoint();

indiceFila = tb_tablaArchivo.rowAtPoint(puntoFC);

ListaArchivo listaArchivo = new ListaArchivo();

ArrayList<Archivo> arreglo;

if (tb_tablaArchivo.getValueAt(indiceFila, 2).equals("Comercial")) {

arreglo = listaArchivo.leerArchivo(archivoComercial);

} else if (tb_tablaArchivo.getValueAt(indiceFila,

2).equals("Explotación")) {

arreglo = listaArchivo.leerArchivo(archivoExplotacion);

} else {

arreglo = listaArchivo.leerArchivo(archivoMarketing);

}

for (int i = 0; i < arreglo.size(); i++) {

if (arreglo.get(i).getIdentificador() ==

Integer.parseInt(tb_tablaArchivo.getValueAt(indiceFila, 0).toString())) {

txt_identificador.setText(arreglo.get(i).getIdentificador() +

"");

txt_cedula.setText(arreglo.get(i).getCedula());

txt_fecha.setText(arreglo.get(i).getFechaNacimiento());

cmb_departamento.setSelectedIndex(arreglo.get(i).getDepartamento() - 1);

cmb_sexo.setSelectedIndex(arreglo.get(i).getSexo() - 1);

txt_lugar.setText(arreglo.get(i).getLugar());

txt_nombre.setText(arreglo.get(i).getNombre());

txt_apellido.setText(arreglo.get(i).getApellido());

txt_direccion.setText(arreglo.get(i).getDireccion());

txt_correo.setText(arreglo.get(i).getCorreo());

txt_contacto.setText(arreglo.get(i).getContacto());

auxDepart = cmb_departamento.getSelectedIndex() + 1;

cadenaAntigua = txt_identificador.getText() + ";" +

txt_cedula.getText() + ";" + txt_fecha.getText() + ";"

+ (cmb_departamento.getSelectedIndex() + 1) + ";" +

(cmb_sexo.getSelectedIndex() + 1) + ";" + txt_lugar.getText() + ";"

+ txt_nombre.getText() + ";" + txt_apellido.getText() +

";" + txt_direccion.getText() + ";" + txt_correo.getText() + ";"

+ txt_contacto.getText();

break;

}

}

Page 49: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

42

activarBotones(true);

} else {

}

} catch (Exception e) {

System.out.print("NO SE HA CARGADO EL ARCHIVO");

}

}

private void activarCajas(boolean x) {

txt_cedula.setEnabled(x);

txt_apellido.setEnabled(x);

txt_contacto.setEnabled(x);

txt_correo.setEnabled(x);

txt_direccion.setEnabled(x);

txt_fecha.setEnabled(x);

txt_lugar.setEnabled(x);

txt_nombre.setEnabled(x);

cmb_sexo.setEnabled(x);

}

private void activarBotones(boolean x) {

btn_nuevo.setEnabled(!x);

bt_editar.setEnabled(x);

btn_cancelar.setEnabled(x);

btn_guardar.setEnabled(!x);

btn_eliminar.setEnabled(x);

btn_departamento.setEnabled(!x);

btn_leerArchivo.setEnabled(!x);

btn_crearArbol.setEnabled(!x);

}

private void btn_eliminarActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

if (editar == 1) {

ListaArchivo listaArchivo = new ListaArchivo();

String cadena = txt_identificador.getText() + ";" + txt_cedula.getText() + ";"

+ txt_fecha.getText() + ";"

+ (cmb_departamento.getSelectedIndex() + 1) + ";" +

(cmb_sexo.getSelectedIndex() + 1) + ";" + txt_lugar.getText() + ";"

+ txt_nombre.getText() + ";" + txt_apellido.getText() + ";" +

txt_direccion.getText() + ";" + txt_correo.getText() + ";"

+ txt_contacto.getText();

switch (cmb_departamento.getSelectedIndex()) {

case 0: {

listaArchivo.eliminarRegistro(archivoComercial, cadena);

break;

}

case 1: {

listaArchivo.eliminarRegistro(archivoExplotacion, cadena);

break;

}

case 2: {

listaArchivo.eliminarRegistro(archivoMarketing, cadena);

break;

}

}

}

limpiar();

activarBotones(false);

btn_guardar.setEnabled(false);

}

private void btn_crearArbolActionPerformed(java.awt.event.ActionEvent evt) {

MenuArbol menuArbol = new MenuArbol(new MenuArchivo(), true);

menuArbol.setLocationRelativeTo(null);

menuArbol.setVisible(true);

}

private void bt_editarActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

editar = 1;

auxDepart = cmb_departamento.getSelectedIndex() + 1;

Page 50: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

43

activarCajas(true);

btn_guardar.setEnabled(true);

btn_eliminar.setEnabled(false);

bt_editar.setEnabled(false);

}

private void btn_departamentoActionPerformed(java.awt.event.ActionEvent evt) {

MenuDepartamento menuDepartamento = new MenuDepartamento(new MenuArchivo(), true);

menuDepartamento.setLocationRelativeTo(null);

menuDepartamento.setVisible(true); // TODO add your handling code here:

}

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code

(optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default

look and feel.

* For details see

http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

try {

for (javax.swing.UIManager.LookAndFeelInfo info :

javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

}

}

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(MenuArchivo.class.getName()).log(java.util.logging.Le

vel.SEVERE, null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(MenuArchivo.class.getName()).log(java.util.logging.Le

vel.SEVERE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(MenuArchivo.class.getName()).log(java.util.logging.Le

vel.SEVERE, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(MenuArchivo.class.getName()).log(java.util.logging.Le

vel.SEVERE, null, ex);

}

//</editor-fold>

/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new MenuArchivo().setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.JButton bt_editar;

private javax.swing.JButton btn_cancelar;

private javax.swing.JButton btn_crearArbol;

private javax.swing.JButton btn_departamento;

private javax.swing.JButton btn_eliminar;

private javax.swing.JButton btn_guardar;

private javax.swing.JButton btn_leerArchivo;

private javax.swing.JButton btn_nuevo;

private javax.swing.JComboBox cmb_departamento;

private javax.swing.JComboBox cmb_sexo;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel10;

private javax.swing.JLabel jLabel11;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

Page 51: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

44

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel5;

private javax.swing.JLabel jLabel6;

private javax.swing.JLabel jLabel7;

private javax.swing.JLabel jLabel8;

private javax.swing.JLabel jLabel9;

private javax.swing.JPanel jPanel1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JScrollPane jScrollPane2;

private javax.swing.JTable tb_tablaArchivo;

private javax.swing.JTextField txt_apellido;

private javax.swing.JTextField txt_cedula;

private javax.swing.JTextField txt_contacto;

private javax.swing.JTextField txt_correo;

private javax.swing.JTextArea txt_direccion;

private javax.swing.JTextField txt_fecha;

private javax.swing.JTextField txt_identificador;

private javax.swing.JTextField txt_lugar;

private javax.swing.JTextField txt_nombre;

// End of variables declaration

}

package interfaz;

import arbolavl.*;

import java.awt.Point;

import java.io.File;

import java.util.ArrayList;

import javax.swing.table.DefaultTableModel;

/** @author ISRAEL */

public class MenuDepartamento extends javax.swing.JDialog {

public MenuDepartamento(java.awt.Frame parent, boolean modal) {

super(parent, modal);

initComponents();

//arbolAVL.inOrden(arbol1);

}

File archivoLaboral = new File("D:\\laboral.txt");

/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();

tb_departamento = new javax.swing.JTable();

btn_visualizar = new javax.swing.JButton();

jButton1 = new javax.swing.JButton();

jLabel1 = new javax.swing.JLabel();

jLabel2 = new javax.swing.JLabel();

jLabel3 = new javax.swing.JLabel();

txt_identificador = new javax.swing.JTextField();

txt_origen = new javax.swing.JTextField();

txt_destino = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

setTitle("Gestión de Departamentos");

tb_departamento.setModel(new javax.swing.table.DefaultTableModel(

new Object [][] {

{null, null, null},

{null, null, null},

{null, null, null},

{null, null, null}

},

new String [] {

"Identificador", "Depart. Origen", "Depart. Destino"

}

));

Page 52: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

45

tb_departamento.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent evt) {

tb_departamentoMouseClicked(evt);

}

});

jScrollPane1.setViewportView(tb_departamento);

btn_visualizar.setText("Listar");

btn_visualizar.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btn_visualizarActionPerformed(evt);

}

});

jButton1.setIcon(new

javax.swing.ImageIcon(getClass().getResource("/iconos/iconos/delete.png"))); // NOI18N

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

jLabel1.setText("Identificador");

jLabel2.setText("Departamento de Origen");

jLabel3.setText("Departamento de Destino");

txt_identificador.setEditable(false);

txt_origen.setEditable(false);

txt_destino.setEditable(false);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(86, 86, 86)

.addComponent(jButton1)

.addGap(45, 45, 45)

.addComponent(btn_visualizar))

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addComponent(jScrollPane1,

javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(layout.createSequentialGroup()

.addGap(32, 32, 32)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

.addComponent(jLabel3)

.addComponent(jLabel2)

.addComponent(jLabel1))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

.addComponent(txt_identificador)

.addComponent(txt_origen)

.addComponent(txt_destino,

javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE))))

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addGap(12, 12, 12)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

Page 53: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

46

.addComponent(btn_visualizar, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

.addGap(23, 23, 23)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel1)

.addComponent(txt_identificador,

javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel2)

.addComponent(txt_origen, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18, 18, 18)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(jLabel3)

.addComponent(txt_destino, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(18, 18, Short.MAX_VALUE)

.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 136,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap())

);

pack();

}// </editor-fold>

public void dibujarTabla(ArrayList<Departamento> arreglo) {

DefaultTableModel modelo = new DefaultTableModel() {

@Override

public boolean isCellEditable(int row, int col) {

return false;

}

};

Object[] fila = new Object[3];

String[] columnas = {"Identificador", "Depart. Origen", "Depart. Destino"};

modelo.setColumnIdentifiers(columnas);

for (int i = 0; i < arreglo.size(); i++) {

fila[0] = arreglo.get(i).getIdentificador();

fila[1] = arreglo.get(i).getDepartOrigen();

fila[2] = arreglo.get(i).getDepartDestino();

modelo.addRow(fila);

}

tb_departamento.setModel(modelo);

}

private void btn_visualizarActionPerformed(java.awt.event.ActionEvent evt) {

ListaDepartamento listaDepartamento = new ListaDepartamento();

dibujarTabla(listaDepartamento.leerArchivo(archivoLaboral));

}

private void tb_departamentoMouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

Point puntoFC;

int indiceFila = 0;

try {

if (evt.getClickCount() == 2) {

puntoFC = evt.getPoint();

indiceFila = tb_departamento.rowAtPoint(puntoFC);

ListaDepartamento listaDepartamento = new ListaDepartamento();

ArrayList<Departamento> arreglo =

listaDepartamento.leerArchivo(archivoLaboral);

for (int i = 0; i < arreglo.size(); i++) {

if

(arreglo.get(i).getIdentificador().equals(tb_departamento.getValueAt(indiceFila,

0).toString())) {

txt_identificador.setText(arreglo.get(i).getIdentificador() +

"");

Page 54: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

47

txt_origen.setText(arreglo.get(i).getDepartOrigen());

txt_destino.setText(arreglo.get(i).getDepartDestino());

break;

}

}

}else{}

} catch (Exception e) {

System.out.print("NO SE HA CARGADO EL ARCHIVO");

}

}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

ListaDepartamento lista = new ListaDepartamento();

String cadena = txt_identificador.getText() + ";" + txt_origen.getText() + ";" +

txt_destino.getText();

lista.eliminarRegistro(archivoLaboral, cadena);

txt_identificador.setText(null);

txt_origen.setText(null);

txt_destino.setText(null);

}

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code

(optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default

look and feel.

* For details see

http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

try {

for (javax.swing.UIManager.LookAndFeelInfo info :

javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

}

}

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(MenuDepartamento.class.getName()).log(java.util.loggi

ng.Level.SEVERE, null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(MenuDepartamento.class.getName()).log(java.util.loggi

ng.Level.SEVERE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(MenuDepartamento.class.getName()).log(java.util.loggi

ng.Level.SEVERE, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(MenuDepartamento.class.getName()).log(java.util.loggi

ng.Level.SEVERE, null, ex);

}

//</editor-fold>

/* Create and display the dialog */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

MenuDepartamento dialog = new MenuDepartamento(new javax.swing.JFrame(),

true);

dialog.addWindowListener(new java.awt.event.WindowAdapter() {

@Override

public void windowClosing(java.awt.event.WindowEvent e) {

System.exit(0);

}

});

dialog.setVisible(true);

}

});

Page 55: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

48

}

// Variables declaration - do not modify

private javax.swing.JButton btn_visualizar;

private javax.swing.JButton jButton1;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JTable tb_departamento;

private javax.swing.JTextField txt_destino;

private javax.swing.JTextField txt_identificador;

private javax.swing.JTextField txt_origen;

// End of variables declaration

}

Page 56: UNIDAD ACADÉMICA DE INGENIERÍA CIVIL CARRERA DE …repositorio.utmachala.edu.ec/bitstream/48000/4735/1... · 2016-06-10 · structure of binary trees AVL using the Java programming

49

Anexo 3. Caso de Investigación

Una empresa de servicios tiene tres departamentos: comercial(1), explotación(2)

y marketing(3). Cada empleado está adscrito a uno de ellos. Se ha realizado una

redistribución del personal entre ambos departamentos, los cambios están

guardados en el archivo laboral. txt. El archivo contiene en cada registro los

campos identificador, origen, destino. El campo origen puede tomar los valores

1, 2, 3 dependiendo del departamento origen del empleado, cuya identificación

es una secuencia de 5 dígitos que es el primer campo del registro. El campo

destino también puede tomar los valores 1, 2, 3 según el departamento al que

sea destinado. Escribir un programa que guarde los registros del archivo en tres

árboles AVL, uno por cada departamento origen, y realice los intercambios de

registros en los árboles según el campo destino.