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
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