'Construct BST array (with null elements) from array of int values
I have a task that I have been working on for hours. I have some array of elements (let's say 10, 8, 4, 7, 3, 5, 10, 15, 2, -2, 4) from which I am supposed to make an array reflecting the BST tree with all the elements (no elements, i.e. children are marked as null). In the picture you can see a tree drawn up, and on the right there is an array (not entirely correct) that I want to create in Java as a result of my work. At the same time, I am not allowed to use any variables, objectivity, classed etc. just do it with a for loop (od for loops). I also attach my code where are my attempts to fix the problem are located, but unfortunately it fails. I would be grateful for any tips.
public static int[] listOfBinaryTree(){
int[] arr = new int[]{10, 8, 4, 7, 3, 5, 10, 15, 2, -2, 4};
int[] binaryArr = new int[200];
binaryArr[0] = arr[0];
List<Integer> list = new ArrayList<>();
list.add(arr[0]);
for (int i = 1; i < arr.length; i++) {
if (arr[i] <= binaryArr[i-1] && binaryArr[2*(i-1)+1] == 0){
binaryArr[2*(i-1)+1] = arr[i];
} else if (arr[i] > binaryArr[i-1] && binaryArr[2*(i-1)+2] == 0) {
binaryArr[2*(i-1)+2] = arr[i];
}
else {
for (int j = i; j < binaryArr.length; j++) {
System.out.println("druga" + Arrays.toString(binaryArr));
if (arr[i] <= binaryArr[j] && binaryArr[2*(j)+1] == 0){
binaryArr[2*(j)+1] = arr[i];
} else if (arr[i] > binaryArr[j] && binaryArr[2*(j)+2] == 0) {
binaryArr[2*(j)+2] = arr[i];
}
}
}
}
return binaryArr;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
