动态二进制树形搜索算法Java编程实现,包含主程序
时间: 2024-02-07 20:04:11 浏览: 83
Binary-Search-Tree-Over-Array-Algorithm:该项目是执行诸如二进制搜索算法之类的算法的执行程序
以下是包含主程序的Java代码实现动态二进制树形搜索算法:
```java
import java.util.Scanner;
class DynamicBinaryTree {
private Node root;
private class Node {
private int data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
public DynamicBinaryTree() {
root = null;
}
public void insert(int data) {
if (root == null) {
root = new Node(data);
return;
}
Node current = root;
while (true) {
if (data < current.data) {
if (current.left == null) {
current.left = new Node(data);
return;
}
current = current.left;
} else {
if (current.right == null) {
current.right = new Node(data);
return;
}
current = current.right;
}
}
}
public boolean search(int data) {
Node current = root;
while (current != null) {
if (data == current.data) {
return true;
} else if (data < current.data) {
current = current.left;
} else {
current = current.right;
}
}
return false;
}
}
public class Main {
public static void main(String[] args) {
DynamicBinaryTree tree = new DynamicBinaryTree();
// 插入数据
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(1);
tree.insert(9);
// 搜索数据
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要查找的数据:");
int data = scanner.nextInt();
if (tree.search(data)) {
System.out.println("找到了!");
} else {
System.out.println("没找到!");
}
}
}
```
在主程序中,我们首先创建了一个 `DynamicBinaryTree` 对象,然后插入了一些数据。接着,我们从控制台读取用户输入的数据,并调用 `search` 方法搜索数据。最后,根据搜索结果输出相应的提示信息。
阅读全文