OVH Cloud OVH Cloud

arbre

3 réponses
Avatar
Rodolphe
Je cherche à programmer un arbre mais je n'y arrive pas

J'ai l'erreur:

Hello
Exception in thread "main" java.lang.NullPointerException
at arbre.ajouter(arbre.java:9)
at arbre.main(arbre.java:17)

Voila mon code source:

public class arbre{
Object racine;
arbre gauche;
arbre droite;
public arbre ajouter(Object o){
if(this.racine==null){
this.racine=o;
}else{
this.droite.ajouter(o); //ligne 9
}
return this;
}
public static void main(String[] args){
arbre arbre1=new arbre();
arbre1.ajouter("Hello");
System.out.println(arbre1.racine);
arbre1.ajouter("Hello"); //ligne 17
}
}

3 réponses

Avatar
Pierrot
Rodolphe wrote:
Je cherche à programmer un arbre mais je n'y arrive pas

J'ai l'erreur:

Hello
Exception in thread "main" java.lang.NullPointerException
at arbre.ajouter(arbre.java:9)
at arbre.main(arbre.java:17)

Voila mon code source:

public class arbre{
Object racine;
arbre gauche;
arbre droite;
public arbre ajouter(Object o){
if(this.racine==null){
this.racine=o;
}else{
this.droite.ajouter(o); //ligne 9


ben oui ... this.droite est pas instancié ! Attention : nous ne sommes
pas en C++ .... "arbre droite" déclare un pointeur, mais ne crée pas
l'objet en question !

}
return this;
}
public static void main(String[] args){
arbre arbre1=new arbre();
arbre1.ajouter("Hello");
System.out.println(arbre1.racine);
arbre1.ajouter("Hello"); //ligne 17
}
}



Avant toute chose : quel type d'arbre veux tu faire ? arbre de recherche
? tas ? Quelle est son utilisation ? parceque là, avec cette stratégie
d'insertion a droite, tu vas avoir des problèmes d'équilibre (et au lieu
d'une recherche en k.log(n), tu vas avoir une recherche en k.n ).


bon, le corrigé =)

public class arbre{
Object racine = null;
arbre gauche = null;
arbre droite = null;
public arbre ajouter(Object o){
if(this.racine==null){
this.racine=o;
}else{
if( this.droite = null ) this.droite = new arbre();
this.droite.ajouter(o); //ligne 9




}
return this;
}
public static void main(String[] args){
arbre arbre1=new arbre();
arbre1.ajouter("Hello");
System.out.println(arbre1.racine);
arbre1.ajouter("Hello"); //ligne 17
}
}




Avatar
Pierrot
Pierrot wrote:

....
}else{
if( this.droite = null ) this.droite = new arbre();
this.droite.ajouter(o); //ligne 9




}
return this;
...


AAAARRRRRGGGHH le boulet !!!!!!!

il fallait lire :

if( this.droite == null ) this.droite = new arbre();

désolé =)





Avatar
Rodolphe
Pierrot wrote:

....
}else{
if( this.droite = null ) this.droite = new arbre();
this.droite.ajouter(o); //ligne 9




}
return this;
...



AAAARRRRRGGGHH le boulet !!!!!!!

il fallait lire :

if( this.droite == null ) this.droite = new arbre();

désolé =)


merci !!!
je débute en java, en cours on vient jsute de commencer les arbres de
recherches, je voulais juste ajouter dans le fils droit et après ajouter
la sélection entre fils gauche et droit si ça marchait