使用数组的java中的BST

时间:2017-12-10 03:38:27

标签: java

我正在尝试编写一个二进制搜索算法,搜索并插入数组这里是代码。我所做的是正确移动索引2次,左边是1.这是代码。我还想知道搜索方法是否比逐个遍历数组的迭代循环更快?

 public class BinaryTree {
    int root =0;
    int right = 2;
    int left = 1;
    int arr[];
    public void search(int arr[], int value){
        if(arr[right] == value){
            System.out.println("found");
            return;
        }
        if(arr[left] == value){
            System.out.println("found");
            return;
        }
        else{
            left+=1;
            right+=2;
        }

    }

    public void insert(int value, int arr[]) {
            this.arr = arr;

            if(arr[0]==0){
                arr[0] = value;
                root = arr[0];
                System.out.println(root);
            }

            if(value>root){
                if(arr[right]==0){
                 arr[right] = value;
                 right+=2;
                }

            }
            if(value<root){
                if(arr[left]==0){
                    arr[left] = value;
                    left+=1;
                    }else{
                        left+=1;
                    }
            }

    }
    public void printint(){
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]);

        }
    }
    public static void main(String args[]) {
        int tol[] = new int[9];
        BinaryTree tree = new BinaryTree();
      tree.insert(4, tol);
        tree.insert(9,tol);
        tree.insert(9, tol);
        tree.insert(2, tol);
        tree.search(tol, 9);
        tree.printint();
    }

}

这被认为是二进制搜索树吗?

1 个答案:

答案 0 :(得分:0)

我认为你要做的事情有一个特定的术语。你当前实现它的方式,当arr [left]或arr [right]不是0时,它将无法插入。你需要使用某种类型的while循环来重试你的指数后增加

后续插入将起作用,因为您只是增加了左/右值,但是您将值增加错误的值并且您将开始覆盖值。你需要增加到(index * 2)+ 1为左和(index * 2)+ 2为右。

搜索的速度与平衡&#34;的比例会更快。树是。完全不平衡的树不会更快,平衡的树将是ln(n)(我认为)。

left *= 2;
left += 1;

right *= 2;
right += 2;

index  depth element
0      0     ROOT
1      1     L1
2      1     R1
3      2     L1L2
4      2     L1R2
5      2     R1L2
6      2     R1R2
7      3     L1L2L3
8      3     L1L2R3
9      3     L1R2L3
10     3     L1R2R3
11     3     R1L2L3
12     3     R1L2R3
13     3     R1R2L3
14     3     R1R2R3