用java写一个二分查找树
时间: 2023-05-24 07:01:26 浏览: 64
好的,以下是用 Java 写一个二分查找树的基本代码:
```java
class Node {
int key;
Node left, right;
public Node(int data) {
key = data;
left = right = null;
}
}
class BinarySearchTree {
Node root;
public BinarySearchTree() {
root = null;
}
void insert(int key) {
root = insertNode(root, key);
}
Node insertNode(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key) {
root.left = insertNode(root.left, key);
} else if (key > root.key) {
root.right = insertNode(root.right, key);
}
return root;
}
void inorder() {
inorderTraversal(root);
}
void inorderTraversal(Node root) {
if (root != null) {
inorderTraversal(root.left);
System.out.print(root.key + " ");
inorderTraversal(root.right);
}
}
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
bst.insert(50);
bst.insert(30);
bst.insert(20);
bst.insert(40);
bst.insert(70);
bst.insert(60);
bst.insert(80);
System.out.println("Inorder traversal of the binary search tree: ");
bst.inorder();
}
}
```
这里我们定义了一个节点(Node)类和一个二分查找树(BinarySearchTree)类。节点类存储了键值以及左右子节点;而二分查找树类则包含了对节点的插入(insert)和中序遍历(inorder)方法。
我们在 main() 方法中创建了一颗二分查找树,插入了一些数据,并且打印了中序遍历结果。
希望这份代码可以帮到您。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)