Java 将BST转换为阵列
我已经找遍了,似乎找不到任何帮助。。对于一个学校项目,我有一个BST树,我必须将树中的所有int放入一个名为BSTarray的int数组中。Java 将BST转换为阵列,java,arrays,tree,Java,Arrays,Tree,我已经找遍了,似乎找不到任何帮助。。对于一个学校项目,我有一个BST树,我必须将树中的所有int放入一个名为BSTarray的int数组中。这就是我目前所拥有的: public int [] toBSTArray() { int size = 20; int [] BSTarray = new int [size]; for(int i = 0; i <size; i++) { makeArray(root); BSTarray[i]
这就是我目前所拥有的:
public int [] toBSTArray() {
int size = 20;
int [] BSTarray = new int [size];
for(int i = 0; i <size; i++) {
makeArray(root);
BSTarray[i] = root.getValue();
}
return BSTarray;
}
//helper method called by toBSTArray
public void makeArray(BinarySearchTreeNode node) {
if (node != null) {
makeArray(node.getLeft());
makeArray(node.getRight());
// System.out.print(node.getValue() + " ");
}
}
public int[]tobstaray(){
int size=20;
int[]BSTarray=新的int[size];
对于(int i=0;i请尝试以下方法:
Integer[] values = extractValues(n).toArray(new Integer[] {});
使用该方法定义:
private static List<Integer> extractValues(Node n) {
List<Integer> result = new ArrayList<>();
if (n.getLeft() != null) {
result.addAll(extractValues(n.getLeft()));
}
if (n.getRight() != null) {
result.addAll(extractValues(n.getRight()));
}
result.add(n.getValue());
return result;
}
private static int extractValues(Node n, int[] results, int index) {
if (n.getLeft() != null) {
index = extractValues(n.getLeft(), results, index);
}
if (n.getRight() != null) {
index = extractValues(n.getRight(), results, index);
}
results[index] = n.getValue();
return index + 1;
}
使用方法定义:
private static List<Integer> extractValues(Node n) {
List<Integer> result = new ArrayList<>();
if (n.getLeft() != null) {
result.addAll(extractValues(n.getLeft()));
}
if (n.getRight() != null) {
result.addAll(extractValues(n.getRight()));
}
result.add(n.getValue());
return result;
}
private static int extractValues(Node n, int[] results, int index) {
if (n.getLeft() != null) {
index = extractValues(n.getLeft(), results, index);
}
if (n.getRight() != null) {
index = extractValues(n.getRight(), results, index);
}
results[index] = n.getValue();
return index + 1;
}
请注意,结果将出现在results
中。在此之前,必须假定大小大于节点数,或者必须通过遍历树进行计数。如何:(递归不会对数组进行任何更改)
我在makeArray的方法签名中遇到编译错误,它说我需要一个标识符,在BStarray之后我们不允许使用“List”谢谢!我们必须从驱动程序类调用它,所以我再次使用extractValue(n,results,0)创建Tobstaray方法;我有数组“results”返回,但最终打印到控制台,如下所示:[I@66780515The[I@66780515
似乎只是整数数组的字符串表示形式。不幸的是,标准Java在打印数组时不会显示所有值,而只显示[I@66780515
如果括号表示它是一个数组,I
表示整数,数字只是对象的哈希代码。