[英]How to implement Binary Search Tree using an unsorted array with this specific formula?
我需要使用一個數組來實現具有特定公式的二叉搜索樹:根是tree [0]。 對於tree [n]處的任何節點,將在tree [2n + 1](左分支)和tree [2n + 2](右分支)處找到n的子節點(如果有)。 我被允許創建第二個數組來存儲BST。 我得到一個偽代碼:
for(i=1;i<;i++) {
//Every iteration we start from the root node
while (the cell is not empty){
if(less than the element)
go to 2i+1;
else if (greater than the element)
go to 2i+2;
到目前為止,這是我腦力激盪的:
public class BinarySearchTree {
public void createBST(int[] array) {
int[] tree = new int[array.length];
int root = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] < root) {
tree[(2*i)+1] = array[i];
} else {
array[(2 * i) + 2];
}
}
}
}
我不知道從這里去哪里。 我已經花了一段時間沒有解決辦法。 任何幫助表示贊賞。 謝謝。
該偽代碼永遠不會創建樹。
任何數組值僅與比較相關,有趣的信息是索引。 同樣,“轉到”修改位置。 該位置需要存儲在某個位置(並從根開始)。
Integer[] tree = new Integer[array.length]
//the element to add is array[i]
for (int i = 0; i < array.length; ++i) {
//every iteration starts from the root node
int pos = 0;
//while the cell is not empty
while (tree[pos] != null) {
//if the cell is smaller than the element
if (tree[pos] < array[i]) {
//go to 2n+1
pos = 2 * pos + 1;
} else {
//go to 2n+2
pos = 2 * pos + 2;
}
}
//add at the empty position.
tree[pos] = array[i];
}
注意:我沒有對此進行測試,它可能會在某個時候拋出ArrayIndexOutBoundException。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.