2017-04-08 27 views
0

我需要使用数组来实现具有特定公式的二进制搜索树:root是tree [0]。对于tree [n]处的任何节点,将在树[2n + 1](左分支)和树[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]; 
      } 
     } 
    } 
} 

我不知道在哪里可以从这里走。我一直在这一段时间没有解决方案。任何帮助表示赞赏。谢谢。

回答

0

该伪代码永远不会创建树。

任何数组值只与比较有关,有趣的信息是索引。此外,“去”修改一个位置。该位置需要存储在某处(并从根开始)。

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一个某一点。

+0

非常感谢!我运行了代码,并且有一个ArrayIndexOutOfBoundException。我试着改变array.length并添加一个额外的if语句,当pos> array.length但没有结果。我认为这可能是while循环语句。你有什么想法如何解决这个问题? – Jen

+0

潜在的问题是,通过跟随伪代码添加序列'1; 2; 3; 4'将被存储在位置'0; 2; 6; 14'中,但是该阵列只有4个长。愚蠢的解决方案是让阵列足够大。其他解决方案:某种平衡,或_sorting_'array'成为一个二叉搜索树(效率不高,但保证工作)。我忘了问的是:数组排序? – Poohl

+0

我只是调试我的程序,看看你在说什么。不,数组没有排序。我的教授说他不希望数组被排序。对不起,我忘了提及一些事情:如果节点没有左边和/或右边的孩子,相应的位置应该是-1。我需要做更大的阵列吗? – Jen