|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Member
Iscritto dal: Oct 2012
Messaggi: 59
|
[JAVA] Aggiungere un nodo ad un albero binario
Ciao
![]() Devo scrivere un metodo che aggiunga un nodo ad un albero binario. Codice:
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; } } Chi mi aiuta? Grazie |
![]() |
![]() |
![]() |
#2 |
Senior Member
Iscritto dal: Nov 2005
Messaggi: 2775
|
A occhio mi sembra che dovresti fare così
Codice:
root = add(element, path, root ); 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)... |
![]() |
![]() |
![]() |
#3 |
Member
Iscritto dal: Oct 2012
Messaggi: 59
|
Grazie per l'aiuto!
Codice:
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; } Codice:
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 Ultima modifica di vfldj : 26-10-2012 alle 22:22. |
![]() |
![]() |
![]() |
#4 |
Senior Member
Iscritto dal: Nov 2005
Messaggi: 2775
|
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.
|
![]() |
![]() |
![]() |
#5 |
Member
Iscritto dal: Oct 2012
Messaggi: 59
|
|
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 09:50.