elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


  Mostrar Mensajes
Páginas: [1] 2
1  Programación / PHP / Problema con conexion de Yii Framework a SQLServer en: 29 Enero 2016, 15:16 pm
Estoy intentando conectar Yii con SQLSERVER y me sale este error.

Código
  1. CDbException
  2.  
  3. CDbConnection failed to open the DB connection.

Esto es lo que tengo en el COMMON/Config/main.php

Código
  1. <?php
  2.  
  3. return array(
  4.    'preload' => array('log', 'bootstrap'),
  5.    'aliases' => array(
  6.        'frontend' => dirname(__FILE__) . '/../..' . '/frontend',
  7.        'common' => dirname(__FILE__) . '/../..' . '/common',
  8.        'backend' => dirname(__FILE__) . '/../..' . '/backend',
  9.        'vendor' => dirname(__FILE__) . '/../..' . '/common/lib/vendor',
  10.        'bootstrap' => dirname(__FILE__) . '/../..' . '/common/lib/vendor/clevertech/yii-booster/src',
  11.        'auth' => dirname(__FILE__) . '/../..' . '/backend/modules/auth'
  12.    ),
  13.    'import' => array(
  14.        'common.extensions.components.*',
  15.        'common.components.*',
  16.        'common.helpers.*',
  17.        'common.models.*',
  18.        'application.controllers.*',
  19.        'application.extensions.*',
  20.        'application.helpers.*',
  21.        'application.models.*',
  22.        'common.gii.*'
  23.    ),
  24.    'language' => 'es',
  25.    //'behaviors' => array('LanguageBehavior'),
  26.    'components' => array(
  27.        'db' => array(
  28.            //'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
  29.            //'connectionString' => 'mysql:host=192.168.0.117;dbname=yiiBase',
  30.            'connectionString' => 'sqlsrv:server=SOPORTE03\SQLEXPRESS;database=seguimiento',
  31.            //'emulatePrepare' => true,
  32.            'username' => 'sa',
  33.            'password' => 'jean1234',
  34.            //'charset' => 'utf8',
  35.            'tablePrefix' => 'dbo.',
  36.        ),
  37.        'errorHandler' => array(
  38.            'errorAction' => 'site/error',
  39.        ),
  40.        'bootstrap' => array(
  41.            'class' => 'common.lib.vendor.clevertech.yii-booster.src.components.Bootstrap',
  42.        ),
  43.        'log' => array(
  44.            'class' => 'CLogRouter',
  45.            'routes' => array(
  46.                array(
  47.                    'class' => 'CDbLogRoute',
  48.                    'connectionID' => 'db',
  49.                    'levels' => 'error, warning',
  50.                ),
  51.            ),
  52.        ),
  53.    ),
  54.    'params' => array(
  55.        // php configuration
  56.        'php.defaultCharset' => 'utf-8',
  57.        'php.timezone' => 'UTC',
  58.    )
  59. );
2  Programación / Java / Re: error en consulta sql en java! en: 21 Octubre 2015, 20:07 pm
La misma documentación que colocaron ahí estaba leyendo, pero no veo que parte esta mal!!!
3  Programación / Java / error en consulta sql en java! en: 21 Octubre 2015, 19:51 pm
Alguien sabe porque me sale este error? He tratado de solucionarlo pero de momento no he podido !!! Saludos!!!


java.sql.SQLException: Operation not allowed after ResultSet closed



Código:
   public  int GenerarIDInfante(){
    int IDGenerado=0;
    
    try {
            operaciones consulta=new operaciones(); //crea un objeto de la clase consulta
            ResultSet resultado=consulta.ConsultaBase("select count(*) as id from documentos"); //
            
              resultado.next();
              IDGenerado=resultado.getInt("id");
              
//          
            consulta.getStmt().close();
            
        } catch (SQLException ex) {
             System.out.println(ex);
        }
    
    return IDGenerado+1;
   }




Mod: No escribir en maýuculas
4  Programación / Programación C/C++ / Lectura de archivo log, error al eliminar IPs duplicadas! en: 8 Junio 2015, 04:31 am
Tengo un problema al eliminar las direcciones IP que se repiten!

Código
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <fstream>
  4. #include <ctime>
  5. #include <string>
  6. #include<cstdio>
  7.  
  8. using namespace std;
  9.  
  10. /*
  11.  *Leer el log y extraer la primera dirección IP  (nnn.nnn.nnn.nnn).
  12.  *Guardar la dirección ip en una lista -evitar que se repite la dirección ip.
  13.  *Resumir cuantas veces se repite cada ip y visualizar en un SVG el resumen.
  14.  */
  15.  
  16. struct miDataStruct {
  17.    string direccionIP;
  18.    int id;
  19. };
  20.  
  21. struct nodo {
  22.    miDataStruct datoDelNodo;
  23.    nodo *ant;
  24.    nodo *next;
  25. };
  26.  
  27.  
  28. //PROTOTIPOS
  29.  
  30. void archivos_lectura(nodo * list);
  31. int getPosition(string linea,int opcion,int ini);
  32. //FUNCIONES DE MI LISTA DOBLE
  33. nodo * new_list();
  34. nodo * insert_right(nodo *list, nodo data);
  35. void printListAsc(nodo *head);
  36. void printListDesc(nodo *head);
  37. void printList(  nodo* list);
  38.  
  39. void borrarNodo(nodo **head, nodo *node);
  40. void removerDuplicado(nodo **head);
  41.  
  42.  
  43.  
  44. int main () {
  45.  
  46. nodo *head = new_list();
  47.     nodo *current = head;
  48.      archivos_lectura(current);
  49.  
  50.      printList( current);
  51.     removerDuplicado(&head);
  52.  
  53.  
  54.  
  55.  return 0;
  56. }
  57.  
  58. nodo * new_list(){
  59.  
  60.    nodo *newelement= new nodo;
  61.    newelement->datoDelNodo.direccionIP = - 1 ;
  62.    newelement->next = newelement;
  63.    newelement->ant = newelement;
  64.    return newelement;
  65.  
  66. }
  67.  
  68. void addList(  nodo *list , string number){    
  69.        nodo *newelement = new nodo;
  70.        newelement->datoDelNodo.direccionIP = number;      
  71.        newelement->next = list;
  72.        newelement->ant = list->ant;
  73.        list->ant = newelement;
  74.        newelement->ant->next = newelement;
  75. }
  76.  
  77.  
  78. void printListAsc(nodo *head) {
  79.    nodo *current = head;
  80.    while (current->next != head) {
  81.        current = current->next;        
  82.        printList(current);      
  83.    }
  84. }
  85.  
  86.  
  87. void printListDesc(nodo *head) {
  88.    nodo *current = head;
  89.    //printNode(current);
  90.    while (current->ant != head) {
  91.        current = current->ant;
  92.        printList(current);
  93.  
  94.    }
  95. }
  96.  
  97. void printList(  nodo* list){
  98. nodo *head = list;
  99. nodo *current = list;
  100. int i=1;
  101. char caracter;
  102. while (current != head->ant){
  103.            current=current->next;
  104.            cout<<"LINEA --------> "<<i++<<endl<<endl;
  105.       cout<<"Numero de IP: "<<current->datoDelNodo.direccionIP<<endl;
  106.       cout<<"__________________________________"<<endl<<endl;
  107.      // caracter = getchar();
  108.       //getch();
  109.        }
  110. cout<< endl ;
  111.  
  112. }
  113.  
  114. // Proceso de los ficheros...
  115.  
  116. //Obteniendo la posicion de los datos del .log        
  117. int getPosition(string linea,int opcion,int ini){
  118.  
  119. int r;
  120.  
  121. switch(opcion) {
  122.    case 1:
  123.        r = linea.find("UDP") + 4;break;
  124.    case 2:
  125.        r=linea.find(" ",ini);break;
  126. }
  127. // -----> En caso de mas parametros a obtener, mas case; <-
  128. return r;
  129. }
  130.  
  131.  
  132. void archivos_lectura(nodo * list) {
  133.  nodo *current=list;  
  134.  
  135.  string line;
  136.  ifstream myfile ("firewall_1.log");
  137.  int p1,p2;
  138.  string numero;
  139.  
  140.  nodo myDataIP;
  141.  
  142.  if (myfile.is_open())
  143.  {
  144.    while ( getline (myfile,line) )
  145.    {
  146.        p1 =getPosition(line,1,0); // p1=29
  147.        p2=getPosition(line,2,p1);
  148.        numero=line.substr(p1,p2-p1);    
  149.        addList(current,numero);
  150.  
  151.        //cout << line << '\n';
  152.    }
  153.  
  154.    myfile.close();
  155.  }
  156.  
  157.  else cout << "Unable to open file";
  158. }
  159.  
  160.  
  161. // FUNCIONES PARA ELIMINAR LOS DUPLICADOS
  162.  
  163. void removerDuplicado(nodo **head)
  164. {
  165. if((*head)->next == NULL) return;
  166. nodo *current = *head;
  167. nodo *aux;
  168. while(current) {
  169. aux = current->next;
  170. while(aux) {
  171. if(current->datoDelNodo.direccionIP == aux->datoDelNodo.direccionIP) {
  172. borrarNodo(head, aux);
  173. }
  174. aux = aux->next;
  175. }
  176. current = current->next;
  177. }
  178. return;
  179. }
  180.  
  181.  
  182.  
  183. void borrarNodo(nodo **head, nodo *node)
  184. {
  185. nodo *current = *head;
  186. nodo *ant = *head;
  187. if(node == *head) {
  188. if((*head)->next != NULL) {
  189. *head = (*head)->next;
  190. }
  191. return;
  192. }
  193. while(current) {
  194. if(current == node) {
  195. ant->next = current->next;
  196. return;
  197. }
  198. ant = current;
  199. current = current->next;
  200. }
  201. }
  202.  
  203.  

//aqui les adjunto el codigo completo con el archivo log para que lo abran como proyecto!
https://mega.co.nz/#F!L8NSyIxZ!RZX98C_HXUVnnwaW30UYFw

Mod: No escribir en mayúsculas
5  Programación / Scripting / Error en busqueda en amplitud con python en: 3 Junio 2015, 18:43 pm
He estado tratando de corregir el error pero no lo encuentro ... Me sale: while nodo.get_padre() != None:
AttributeError: 'NoneType' object has no attribute 'get_padre'


Código
  1. from arbol import Nodo
  2.  
  3. def buscar_solucion_BFS(estado_inicial, solucion):
  4.    solucionado = False
  5.    nodos_visitados = []
  6.    nodos_frontera = []
  7.    nodoInicial = Nodo(estado_inicial)
  8.    nodos_frontera.append(nodoInicial)
  9.    while(not solucionado) and len(nodos_frontera) != 0:
  10.        nodo = nodos_frontera.pop(0)
  11.        #extraer nodo y anadirlo a visitados
  12.        nodos_visitados.append(nodo)
  13.        if nodo.get_datos() == solucion:
  14.            #solucion encontrada
  15.            solucionado = True
  16.            return nodo
  17.        else:
  18.            #expandir nodos hijos
  19.            dato_nodo = nodo.get_datos()
  20.  
  21.            #operador izquierdo
  22.            hijo = [dato_nodo[1], dato_nodo[0], dato_nodo[2], dato_nodo[3]]
  23.            hijo_izquierdo = Nodo(hijo)
  24.            if not hijo_izquierdo.en_lista(nodos_visitados) and not hijo_izquierdo.en_lista(nodos_frontera):
  25.                nodos_frontera.append(hijo_izquierdo)
  26.                #operador central
  27.                hijo = [dato_nodo[0], dato_nodo[2], dato_nodo[1], dato_nodo[3]]
  28.                hijo_central = Nodo(hijo)
  29.                if not hijo_central.en_lista(nodos_visitados) and not hijo_central.en_lista(nodos_frontera):
  30.                    nodos_frontera.append(hijo_central)
  31.                    #operador derecho
  32.                    hijo = [dato_nodo[0], dato_nodo[1], dato_nodo[3], dato_nodo[2]]
  33.                    hijo_derecho = Nodo(hijo)
  34.                    if not hijo_derecho.en_lista(nodos_visitados) and not hijo_derecho.en_lista(nodos_frontera):
  35.                        nodos_frontera.append(hijo_derecho)
  36.  
  37.                        nodo.set_hijos([hijo_izquierdo, hijo_central, hijo_derecho])
  38.  
  39.  
  40. if __name__ == "__main__":
  41.    estado_inicial = [4, 2, 3, 1]
  42.    solucion = [1, 2, 3, 4]
  43.    nodo_solucion = buscar_solucion_BFS(estado_inicial, solucion)
  44.        #mostrar resultado
  45.    resultado = []
  46.    nodo = nodo_solucion
  47.    while nodo.get_padre() != None:
  48.        resultado.append(nodo.get_datos())
  49.        nodo = nodo.get_padre()
  50.    resultado.append(estado_inicial)
  51.    resultado.reverse()
  52.  
  53.    print resultado
  54.  
6  Programación / Java / ayuda sencilla de applet en: 13 Mayo 2015, 06:21 am
Mod: lee las reglas del foro, no debes escribir en mayúsculas, los codigos ven en etiquetas GeSHi, las cosas van en su respuesctivo subforo... tema corregido y movido

saludos, tengo un error en mi ejercicio y me gustaria que me ayuden a encontrar el problema; es sobre la resolucion de una ecuacion cuadratica con applets...


Código
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6.  
  7. import java.applet.Applet;
  8. import java.awt.*;
  9. import java.applet.*;
  10. import java.awt.event.*;
  11. import java.lang.Math;
  12.  
  13. /**
  14.  *
  15.  * @author
  16.  */
  17. public class EcuacionApplet extends Applet implements ActionListener {
  18.  
  19.    /**
  20.      * Initialization method that will be called after the applet is loaded into
  21.      * the browser.
  22.      */
  23.    Label l1, l2, l3, l4, l5;
  24.    TextField t1, t2, t3, t4, t5,t6,t7;
  25.    Button b;
  26.  
  27.    public void init() {
  28.        // TODO start asynchronous download of heavy resources
  29.  
  30.        // --> DECLARANDO MIS ETIQUETAS Y CAJAS DE TEXTO
  31.        l1 = new Label("a");
  32.        t1 = new TextField();
  33.  
  34.        l2 = new Label("b");
  35.  
  36.        t2 = new TextField();
  37.  
  38.        l3 = new Label("c");
  39.        t3 = new TextField();
  40.  
  41.        l4 = new Label("Raiz 1");
  42.        t4 = new TextField("  ");
  43.  
  44.        l5 = new Label("Raiz 2");
  45.  
  46.        t5 = new TextField("  ");
  47.  
  48.        b = new Button("CALCULAR");
  49.        t6= new TextField("  ");
  50.        t7= new TextField("  ");
  51.  
  52.     // --> AÑADIENDO BOTONES Y LABELS
  53.        add(l1);
  54.        add(t1);
  55.        add(l2);
  56.        add(t2);
  57.        add(l3);
  58.        add(t3);
  59.        add(b); //-->BOTON
  60.        add(l4);
  61.        add(t4);
  62.        add(l5);
  63.        add(t5);
  64.        add(t6);
  65.        add(t7);
  66.    b.addActionListener(this);
  67.    // TODO overwrite start(), stop() and destroy() methods
  68.    }
  69.  
  70.    //-->OPERACIONES LOGICAS DEL BOTON CALCULAR
  71.    public void actionPerformed(ActionEvent ae) {
  72.  
  73.        // var a=num,b=num2,c=num3
  74. double num=Double.parseDouble(t1.getText());
  75. double num2=Double.parseDouble(t2.getText());
  76. double num3=Double.parseDouble(t3.getText());
  77. // descarga en la variable d el valor de b^2-4ac
  78. double d=(Math.pow(num2,2.0)-(4*num*num3));
  79. // calcula las raices de la ecuación
  80.        double raiz1=((-num2)+Math.sqrt(d))/(2*num);
  81.        double raiz2=((-num2)-Math.sqrt(d))/(2*num);
  82. // compara la variable d
  83. if (d==0)
  84. {
  85. // las raices son igulaes
  86. t6.setText(""+raiz1);
  87. t7.setText(""+raiz2);
  88. }
  89. if (d>0)
  90. {
  91. // tiene 2 raices diferentes
  92. t6.setText(""+raiz1);
  93. t7.setText(""+raiz2);
  94. }
  95.  
  96. if (d<0) //--> CONDICION DE VALORES IMAGINARIOS
  97. {
  98. t6.setText("IMAGINARIA");
  99. t7.setText("IMAGINARIA");
  100. }
  101.  
  102.    }
  103.  
  104.   //---> POSICIONANDO ENCABEZADO
  105.    public void paint(Graphics g) {
  106.        g.drawString("Resolucion Ecuación Cuadratica  aX^2+bx+c=0", 10, 110);
  107.        g.drawString("Lenguaje de Programacion", 11, 130);
  108.  
  109.    }
  110.  
  111. }
7  Programación / Programación C/C++ / Re: Problema al ordenar una Lista Doble(Lectura de XML) en: 23 Febrero 2015, 03:25 am
Aquí les adjunto el archivo XML!

https://www.dropbox.com/s/4y7t6ziweqtfoqq/cd_catalog.xml?dl=0
8  Programación / Programación C/C++ / Problema al ordenar una Lista Doble(Lectura de XML) en: 23 Febrero 2015, 03:21 am
Alguien podría ayudarme a corregir mi error; lo que pasa es que estoy intentando ordenar mi lista Doble que la hice a partir de la lectura de un archivo xml.(La lectura funciona correctamente). Todo funciona hasta que ejecuta la funcion de ordenar y ahi deja de funcionar!

Les agradecería infinitamente si me ayudan a resolver este problema! Igual si encuentro la solución les aviso! Muchas Gracias de antemano!



Código:
#include <iostream>
#include <cstring>
#include <fstream>
#include <cstdlib>


using namespace std;

struct datos {
    string TITLE;
    string ARTIST;
    string COUNTRY;
    string COMPANY;
    float PRICE;
    int YEAR;
};

struct node {
    datos data;
    node *left;
    node *right;
};

string getTagName(string str);
string getTagContent(string str);
node * newList();
node * insert_right(node *list, datos nuevo_nodeo);
void printList(node* list);
void readXML(node *head);
void sortList(node **lista, int rule, bool dsc) ;


int main() {

    node *head = newList();
    node *current = head;

    //LEYENDO MI ARCHIVO XML
    readXML(head);


    cout << "IMPRIMIENDO LISTA" << endl << endl;
    printList(head);
     // Todo funciona hasta que le incorpora la parte para ordenar y la aplicacion deja de funcionar en ese momento!!
    
    
     sortList( &head, 1, true );  // Ordenando por precio, pero no me funciona y no encuentro el error!
    
     return 0;
}

node * newList() {
    node *nuevo;
    nuevo = new node;
    nuevo->data.ARTIST=-1;
     nuevo->data.COMPANY=-1;
      nuevo->data.COUNTRY=-1;
       nuevo->data.PRICE=-1;
        nuevo->data.TITLE=-1;
         nuevo->data.YEAR=-1;
    nuevo->right = nuevo;
    nuevo->left = nuevo;
    return nuevo;
}


string getTagName(string str) {
    int posInit, posFin;
    int delta;
    posInit = str.find("<");
    posFin = str.find(">");
    delta = posFin - posInit;
    return str.substr(posInit + 1, delta - 1);
}

string getTagContent(string str) {

    int posInit, posFin;
    int delta;
    posInit = str.find(">");
    posFin = str.find("</");
    delta = posFin - posInit;

    return str.substr(posInit + 1, delta - 1);
}

node * insert_right(node *list, datos nuevo_nodeo) {
    node *nuevo;
    nuevo = new node;

    nuevo->data.TITLE = nuevo_nodeo.TITLE;
    nuevo->data.ARTIST = nuevo_nodeo.ARTIST;
    nuevo->data.COUNTRY = nuevo_nodeo.COUNTRY;
    nuevo->data.COMPANY = nuevo_nodeo.COMPANY;
    nuevo->data.PRICE = nuevo_nodeo.PRICE;
    nuevo->data.YEAR = nuevo_nodeo.YEAR;

    nuevo->left = list;
    nuevo->right = list->right;
    list->right = nuevo;
    nuevo->right->left = nuevo;
    return nuevo;
}

void printList(node* list) {
    node *head = list;
    node *current = list;

    while (head != (current = current->right)) {
        cout << "------------------------" << endl;
        cout << current->data.TITLE << endl;
        cout << current->data.ARTIST << endl;
        cout << current->data.COUNTRY << endl;
        cout << current->data.COMPANY << endl;
        cout << current->data.PRICE << endl;
        cout << current->data.YEAR << endl;
    }

}

void readXML(node *current) {

    datos nuevo;
    string fileName = "cd_catalog.XML";
    string line;
    string tagName;
    int posInit, posFin;
    int delta;
    int ban = 0;
    cout << "-----archivo XML->" << fileName << "--------" << endl << endl << endl;
    ifstream myFile((char*) fileName.c_str());

    while (getline(myFile, line, '\n')) {
        tagName = getTagName(line);

        if (ban == 0) {
            datos nuevo; //Para acceder a mi estructura facilmente!
        }

        if (tagName.compare("TITLE") == 0) {
            nuevo.TITLE = getTagContent(line);
            ban++;
        } else if (tagName.compare("ARTIST") == 0) {
            nuevo.ARTIST = getTagContent(line);
            ban++;
        } else if (tagName.compare("COUNTRY") == 0) {
            nuevo.COUNTRY = getTagContent(line);
            ban++;
        } else if (tagName.compare("COMPANY") == 0) {
            nuevo.COMPANY = getTagContent(line);
            ban++;
        } else if (tagName.compare("PRICE") == 0) {
            nuevo.PRICE = atof(getTagContent(line).c_str());
            ban++;
        } else if (tagName.compare("YEAR") == 0) {
            nuevo.YEAR = atoi(getTagContent(line).c_str());
            ban++;
        }

        if (ban == 6) {
            current = insert_right(current, nuevo);
            ban = 0;
        }

    }

    myFile.close();
        
}



void sortList(node **lista, int rule, bool dsc) {

    // rule { 1 --> Price, 2 --> year, 3 --> Artis, 4 --> title }

    node *lst = *lista;

    node *sig;

    datos temp;

    //-- Boolean para validar situación de cambio ---//
    bool valid;

    do {

        sig = lst->right;

        while (sig->right != NULL) {

            switch (rule) {

                case 1:


                    valid = dsc ? (lst->data.PRICE > sig->data.PRICE) : (lst->data.PRICE < sig->data.PRICE);

                    break;

                case 2:


                    valid = dsc ? (lst->data.YEAR > sig->data.YEAR) : (lst->data.YEAR < sig->data.YEAR);

                    break;

                case 3:

                    valid = dsc ? (lst->data.ARTIST > sig->data.ARTIST) : (lst->data.ARTIST < sig->data.ARTIST);

                    break;

                case 4:

                    valid = dsc ? (lst->data.TITLE > sig->data.TITLE) : (lst->data.TITLE < sig->data.TITLE);

                    break;

            }

            if (valid) {

                temp = lst->data;

                lst->data = sig->data;

                sig->data = temp;

            }

            sig = sig->right;

        }

        lst = lst->right;

    } while (lst->right != NULL);

}


9  Programación / Programación C/C++ / Re: BUSCAR EL VALOR MAXIMO Y MINIMO DEL ARBOL BINARIO en: 28 Julio 2014, 19:02 pm
Y como haria para mostrar las hojas y los nodos interiores del arbol?

//ESTA FUNCION ESTOY TRABAJANDO ..

int view_NodosInteriores(node *p){
if (p == NULL)
    return 0;
else{
while (p->left != NULL && p->right != NULL)
   
    return p->datos.edad +view_NodosInteriores(p->right) + view_NodosInteriores(p->left);

}
   
   
}
10  Programación / Programación C/C++ / BUSCAR EL VALOR MAXIMO Y MINIMO DEL ARBOL BINARIO en: 27 Julio 2014, 00:09 am
/*
 * File:   firstTree.cpp
 * Author: Estudiantes
 *
 * Created on 17 de julio de 2014, 06:49 PM
 *
 *
 */

//Necesito saber como sacar el valor máximo y mínimo del árbol binario que esta a //continuación graficado. El problema es que mi función solo toma los valores //extremos del arbol( izquierda y derecha) que son hojas!


#include <cstdlib>
#include <iostream>


using namespace std;

/*
 *
 *
 *
 *
 *
 */

struct misDatos{
    string nombre;
    int edad;
    int num;
};

struct node{
    misDatos datos;
    node *left;
    node *right;
};



node * newTree();
node * insert(int data, string name);


int printPreOrden(node* ptr);
int printRoot(node* head);
int printPostOrden(node *ptr);
int printInOrden(node *ptr);
int findMinimumValueLEFT(node* node);
int findMinimumValueRIGHT(node* node);


int size(node *node); //MAXIMO DE NODOS
int maxALTURA(node *node); //ALTURA


node * insert_right( int data);
node * insert_left( int data);
 int contar_hojas(node *p) ;
int nodosInteriores(node *raiz );

node *max(node *n);
node *min(node *n);


int MAXIMOprintPreOrden(node* ptr);



int main() {
   
   //ARBOL 1
   node *raiz = newTree();
   node *current = raiz;
   node *arbol=raiz;
   
   /*
   
 ----> GRAFICO DEL ARBOL BINARIO
   
        A
     /    \
    B      C
  / \    /  \
  D  E  F    G

*/
   
   
        //A=10
        //B=14
        //C=16
        //D=18
        //E=20
        //F=24
        //G=30
   
        arbol->left = insert(14,"B");
        arbol->right = insert(16,"C");

        current=arbol->left;
 
        current->left = insert(50,"D");
        current->right = insert(60,"E");

        current=arbol->right;
       
       
        current->left = insert(24,"F");
        current->right = insert(30,"G");
   
     
   
            cout << "\tR E C O R R I D O  P R E - O R D E N\n";
            printPreOrden(raiz);
   



    //cout<<endl<<endl;
   // cout << "\tR E C O R R I D O  P O S T - O R D E N\n";
    //printPostOrden(raiz);
   
     //cout<<endl<<endl;
    //cout << "\tR E C O R R I D O  I N - O R D E N\n";
   // printInOrden(raiz);
            cout<<endl<<endl<<endl<<endl;
           
 
           
            cout<<"NUMERO DE NODOS: "<<size(raiz)<<endl;
           
            cout<<"ALTURA :  "<<maxALTURA(raiz)<<endl;
           cout<<"NUMERO DE HOJAS: "<<contar_hojas(raiz)<<endl;
           
           cout<<"NODOS INTERIORES: "<<nodosInteriores(raiz)<<endl;
     
           
           
    return 0;
}

//---------------> NEW TREE
node * newTree() {
    node *nuevo;
    nuevo = new node; 
   
    nuevo->datos.nombre= "A";
    nuevo->datos.edad = 10; // 
    nuevo->right = nuevo;
    nuevo->left = nuevo;

    return nuevo;
}

// -------------> INSERTANDO
node* insert(int data, string name) {
   
    node *nuevo;
    nuevo = new node;
    nuevo->datos.edad=data;
    nuevo->datos.nombre=name;
    nuevo->left=NULL; 
    nuevo->right=NULL;

    return nuevo;
}




// -------------> O R D E N A M I E N T O S

// -----> PREORDEN

int printPreOrden(node* ptr) {
   
    node *current = ptr;
   
   
      printRoot(current);     //RAIZ
 
   
      if(current->left!=NULL){
         printPreOrden(current->left);    //IZQUIERDA     
       }
   
    if(current->right!=NULL){
       printPreOrden(current->right);    //DERECHA
    }
    return current->datos.edad;
}





int printPostOrden(node *ptr){
    node *current= ptr;
   
     if(current->left!=NULL){
         printPostOrden(current->left);    //IZQUIERDA     
       }

     if(current->right!=NULL){
       printPostOrden(current->right);    //DERECHA
    }
   
    printRoot(current);   
   
   
}

int printInOrden(node *ptr){
    node *current= ptr;
   
     if(current->left!=NULL){
         printInOrden(current->left);    //IZQUIERDA     
       }
   
      printRoot(current);
   
      if(current->right!=NULL){
       printInOrden(current->right);    //DERECHA
    }
   
 
   
}


//numero de nodos
int size(node *node){
    if(node==NULL)
        return 0;
    else
        return (size(node->left)+1+size(node->right));
}
//altura del arbol
int maxALTURA(node *node){
    if(node==NULL)
        return 0;
    else{
        int s=maxALTURA(node->left);
     int m=maxALTURA(node->right);
     if (s>m)
         return (m+1);
     else
         return (s+1);
    }return (size(node->left)+1+size(node->right));
}



//IMPRIMIENDO RAIZ

int printRoot(node* head)
{
    cout<<"Nombre: "<<head->datos.nombre<<"    Edad: "<< head->datos.edad<<"\n"<<endl;
   
}


//VALORES MAXIMOS Y MINIMOS ERRONEOS
    node *min(node *n) {
        if (n == NULL || n->left == NULL)
            return n;
        else
            return min(n->left);
    }

    node *max(node *n) {
        if (n == NULL || n->left == NULL)
            return n;
        else
            return max(n->left);
    }
   


//-----> CONTAR HOJAS   
int contar_hojas(node *p){
   if (p == NULL)
      return 0;
   else if (p->left == NULL && p->right == NULL)
      return 1;
   else
      return contar_hojas(p->left) + contar_hojas(p->right);
}

//NODOS INTERIORES
   int nodosInteriores(node *raiz ){
      return size(raiz)-contar_hojas(raiz);
}
Páginas: [1] 2
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines