Salve, mi servirebbe un metodo che, dato un albero, restiuisca un array con le chiavi dell'albero.
Vi scrivo la class che ho creato per farvi vedere come è strutturato l'albero ecc
class BSTNode {
public BSTNode left, right;
public int key;
}
public class BSTUtility {
public static void main(String[] args) {
BSTNode root = new BSTNode();
BSTNode a = new BSTNode();
BSTNode b = new BSTNode();
root.key = 20;
root.left = a;
root.right = b;
a.key = 15;
a.left = null;
a.right = null;
b.key = 25;
b.left = null;
b.right = null;
StampaArray(bstToArray(root));
}
// Dato un BST, crea un array delle sue chiavi
public static int[] bstToArray(BSTNode root) {
// Ricerca della dimensione dell'array
int dim = size(root);
if(dim<=0) {
throw new RuntimeException("Albero vuoto");
}
// Riempire l'array con le chiavi dell'albero
int[] arrayKey = riempi(root, dim);
return arrayKey;
}
// Dato un BST e un intero k, crea un array di dimensione k con le chiavi dell'albero
public static int[] riempi(BSTNode root, int k) {
// k > 0
int[] f = new int[k];
for(int i=0; i<f.length; i++) {
// come si implementa?
}
return f;
}
public static int size(BSTNode root) {
if (root == null) return 0;
else return (1 + size(root.left) + size (root.right));
}
public static void StampaArray(int[] x) {
for(int i=0; i<x.length; i++) {
System.out.println(x[i] + " ");
}
}
}
Grazie in anticipo