jueves, 3 de noviembre de 2011

Arbol general

class Nodo {
    int dato;
    Nodo hermanoDer;
    Nodo hijoIzq;
    public Nodo(int dato,Nodo hd, Nodo hi){
        this.dato=dato;
        this.hermanoDer=hd;
        this.hijoIzq=hi;


    }
}

public class ArbolGeneral {
    //Atributos
    private Nodo laRaiz;

    public ArbolGeneral(){
        this.laRaiz=null;
    }

    //Metodos
    public boolean sonIguales(Nodo laRaiz){
        return SonIguales(laRaiz,this.laRaiz);

    }
    public boolean Agregar(String elPath,int elDato){
        if(laRaiz == null) {
            laRaiz = new Nodo(elDato,null,null);
            return true;
        }else{
            Nodo tmp = buscaNodo(elPath);
            if(tmp == null)
                return false;
            else
                return AgregaHermano(tmp,elDato);
        }
    }
    private Nodo buscaNodo(String elPath){
        Nodo tmp1= laRaiz;
        Nodo tmp2 = tmp1;
        StringTokenizer path = new StringTokenizer(elPath,"/");
        int s;
        while(path.hasMoreTokens()){
            s = Integer.parseInt(path.nextToken());
            while(tmp1 !=null){
                if(s== tmp1.dato)
                    break;
                else {
                    tmp2 = tmp1 = tmp1.hermanoDer;
                }
            }
            if(tmp1 == null)
                return tmp1;
            else{
                tmp2 = tmp1;
                tmp1 = tmp1.hijoIzq;
            }
        }
        return tmp2;
    }
    private boolean AgregaHermano(Nodo elPadre, int elDato){
        Nodo tmp = elPadre.hijoIzq;
        if(tmp == null){
            elPadre.hijoIzq = new Nodo(elDato, null, null);
            return true;
        } else{
            elPadre.hijoIzq = new Nodo(elDato, null, elPadre.hijoIzq);
            return true;
        }
    }

    private boolean SonIguales(Nodo a, Nodo b) {
        if(a!=null && b!=null){
            if(a.dato==b.dato){
                SonIguales(a.hermanoDer,b.hermanoDer);
                SonIguales(a.hijoIzq,b.hijoIzq);
                return true;
            }else{
                return false;
            }
        }else{
            return true;
        }
    }
    public static void main(String[] args) {
        ArbolGeneral a= new ArbolGeneral();


    }
}