PDA

View Full Version : [JAVA] Aggiungere un nodo ad un albero binario


vfldj
26-10-2012, 20:07
Ciao :)
Devo scrivere un metodo che aggiunga un nodo ad un albero binario.


public class BinaryTree {

protected class Node {

Integer element;
Node left;
Node right;

Node(int element) {
this.element = element;
left = right = null;
}

Node(int element, Node left, Node right) {
this.element = element;
this.left = left;
this.right = right;
}

boolean isLeaf() {
return left == null && right == null;
}
}

protected Node root;

public BinaryTree() {
root = null;
}

public boolean isEmpty() {
return root == null;
}

/*
Aggiunge un nodo nella posizione indicata da path
*/
public void add(int element, String path) {
add(element, path, ?? );
}

protected Node add(int elem, String path, Node nd) {
if(nd == null)
return new Node(elem);
else {
if(path.length() == 0)
nd.element = elem;
else {
char go = path.charAt(0);
String nextPath = path.substring(1);
if (go == 'L')
nd.left = add(elem, nd.left, nextPath);
else if(go == 'R')
nd.right = add(elem, nd.right, nextPath);
else
System.out.println("Path inadeguato");
}

}
return nd;
}
}


Avevo pensato ad una cosa del genere ma non funziona, più che altro non so come completare il metodo..
Chi mi aiuta?

Grazie

wingman87
26-10-2012, 21:39
A occhio mi sembra che dovresti fare così
root = add(element, path, root );
Dal testo di
Node add(int elem, String path, Node nd)
ho dedotto che se il path va oltre un cammino esistente ti fermi comunque al primo nodo null che trovi.

Per correttezza vorrei sottolineare che non si tratta propriamente di una add ma di un'operazione un po' ibrida (tra aggiunta e modifica)...

vfldj
26-10-2012, 23:19
Grazie per l'aiuto!



public void add(int element, String path) {
root = add(element, path, root);
}

protected Node add(int elem, String path, Node nd) {
if(nd == null)
return new Node(elem);
else {
if(path.length() == 0)
nd.element = elem;
else {
char go = path.charAt(0);
String nextPath = path.substring(1);
if (go == 'L')
nd.left = add(elem, nd.left, nextPath);
else if(go == 'R')
nd.right = add(elem, nd.right, nextPath);
else
System.out.println("Path inadeguato");
}

}
return nd;
}


Compilando questo codice, il compilatore mi da il seguente errore:


cannot find symbol
symbol : method add
nd.left = add(elem, nd.left, nextPath);
^
cannot find symbol
symbol : method add

nd.right = add(elem, nd.right, nextPath);
^
2 errors

wingman87
29-10-2012, 09:56
Credo sia perché hai scambiato il parametro nd con il parametro path. Però mi sembra di ricordare che il tipo di errore in questo caso è diverso... fai una prova.

vfldj
31-10-2012, 22:27
Credo sia perché hai scambiato il parametro nd con il parametro path. Però mi sembra di ricordare che il tipo di errore in questo caso è diverso... fai una prova.

Era proprio quello, che errore stupido!
Grazie :)