用JAVA写一段二叉树功能实现代码
时间: 2023-05-19 15:07:00 浏览: 99
好的,以下是一段用JAVA实现二叉树功能的代码:
```
public class BinaryTree {
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 void insert(int data) {
root = insert(root, data);
}
private Node insert(Node node, int data) {
if (node == null) {
node = new Node(data);
} else {
if (data <= node.data) {
node.left = insert(node.left, data);
} else {
node.right = insert(node.right, data);
}
}
return node;
}
public boolean contains(int data) {
return contains(root, data);
}
private boolean contains(Node node, int data) {
if (node == null) {
return false;
} else if (data == node.data) {
return true;
} else if (data < node.data) {
return contains(node.left, data);
} else {
return contains(node.right, data);
}
}
public void delete(int data) {
root = delete(root, data);
}
private Node delete(Node node, int data) {
if (node == null) {
return null;
}
if (data == node.data) {
if (node.left == null) {
return node.right;
} else if (node.right == null) {
return node.left;
} else {
node.data = findMin(node.right);
node.right = delete(node.right, node.data);
}
} else if (data < node.data) {
node.left = delete(node.left, data);
} else {
node.right = delete(node.right, data);
}
return node;
}
private int findMin(Node node) {
while (node.left != null) {
node = node.left;
}
return node.data;
}
}
```
这段代码实现了二叉树的插入、查找和删除功能。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](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/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)