java实现二叉查找

public class erchachazhao {
public static void print(int[] array,int middle){
int i;
for( i=0;i<array.length;i++){
System.out.print(array[i]);
if (i==middle){
System.out.print("*");
}
System.out.print(" ");}
System.out.println();
}
public static int indexof(int[] array,int value){
int low=0;
int high=array.length-1;
int middle;
while(low<=high)
{   middle=(low+high)/2;
print(array,middle);
if(value<array[middle]){
high=middle-1;
}else if(value==array[middle]){
return middle;
}else{
low=middle+1;
}
}
return -1;
}
public static void main(String[] args){
int[] a=new int[]{2,4,9,13,23,36,46,58,78,94};
System.out.println("location of 46 is:"+indexof(a,46));
System.out.println("location of 9 is:"+indexof(a,9));
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉查找树(Binary Search Tree)是一种常见的数据结构,它的每个节点最多有两个子节点,左子节点的值小于父节点的值,右子节点的值大于父节点的值。Java 实现二叉查找树的代码如下: ``` public class BinarySearchTree { private Node root; private class Node { private int key; private Node left; private Node right; public Node(int key) { this.key = key; } } public void insert(int key) { root = insert(root, key); } private Node insert(Node x, int key) { if (x == null) { return new Node(key); } if (key < x.key) { x.left = insert(x.left, key); } else if (key > x.key) { x.right = insert(x.right, key); } return x; } public boolean contains(int key) { return contains(root, key); } private boolean contains(Node x, int key) { if (x == null) { return false; } if (key == x.key) { return true; } else if (key < x.key) { return contains(x.left, key); } else { return contains(x.right, key); } } public void delete(int key) { root = delete(root, key); } private Node delete(Node x, int key) { if (x == null) { return null; } if (key < x.key) { x.left = delete(x.left, key); } else if (key > x.key) { x.right = delete(x.right, key); } else { if (x.left == null) { return x.right; } else if (x.right == null) { return x.left; } else { Node t = x; x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } } return x; } private Node min(Node x) { if (x.left == null) { return x; } else { return min(x.left); } } private Node deleteMin(Node x) { if (x.left == null) { return x.right; } x.left = deleteMin(x.left); return x; } } ``` 这段代码实现二叉查找树的插入、查找和删除操作。其中,插入操作使用递归实现查找和删除操作也是递归实现的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值