所以我确信这非常简单,我只是错过了它,但我需要为 BST 创建一个未排序的数组。我有一个数组 int[] data = { 50, 30, 60, 10, 80, 55, 40 }; 无论我将其更改为什么,我都需要将其转换为以第一个数字为根的不平衡二叉搜索树,其他数字遵循左右规则。我有这段代码适用于该数组,但如果我将数字更改为不在中间的数字,则无效。
public Node arraytoBinary(int [] array, int start, int end) {
if (start > end){
return null;
}
int mid = (start + end) / 2;
Node node = new Node(array[mid]);
node.left = arraytoBinary(array, start, mid - 1);
node.right = arraytoBinary(array, mid + 1, end);
return node;
}
Run Code Online (Sandbox Code Playgroud)