public class BinaryTree { private Node root; public void insert(int value) { // 实现插入节点的逻辑 } public void traversePreOrder() { // 实现前序遍历的逻辑 } public void traverseInOrder() { // 实现中序遍历的逻辑 } public void traversePostOrder() { // 实现后序遍历的逻辑 } public Node search(int value) { // 实现查找节点的逻辑 } public void delete(int value) { // 实现删除节点的逻辑 } private class Node { int value; Node left; Node right; public Node(int value) { this.value = value; } }}
时间: 2023-05-29 22:04:15 浏览: 97
BST_javaBST_https://bst.91_bstcom_
// 我是AI助手,这是一个二叉树的Java实现代码,包括插入、遍历、查找、删除等操作
public class BinaryTree {
private Node root;
// 插入节点
public void insert(int value) {
Node node = new Node(value);
if (root == null) {
root = node;
} else {
Node current = root;
while (true) {
if (value < current.value) {
if (current.left == null) {
current.left = node;
break;
}
current = current.left;
} else {
if (current.right == null) {
current.right = node;
break;
}
current = current.right;
}
}
}
}
// 前序遍历
public void traversePreOrder() {
traversePreOrder(root);
System.out.println();
}
private void traversePreOrder(Node node) {
if (node != null) {
System.out.print(node.value + " ");
traversePreOrder(node.left);
traversePreOrder(node.right);
}
}
// 中序遍历
public void traverseInOrder() {
traverseInOrder(root);
System.out.println();
}
private void traverseInOrder(Node node) {
if (node != null) {
traverseInOrder(node.left);
System.out.print(node.value + " ");
traverseInOrder(node.right);
}
}
// 后序遍历
public void traversePostOrder() {
traversePostOrder(root);
System.out.println();
}
private void traversePostOrder(Node node) {
if (node != null) {
traversePostOrder(node.left);
traversePostOrder(node.right);
System.out.print(node.value + " ");
}
}
// 查找节点
public Node search(int value) {
Node current = root;
while (current != null && current.value != value) {
if (value < current.value) {
current = current.left;
} else {
current = current.right;
}
}
return current;
}
// 删除节点
public void delete(int value) {
root = delete(root, value);
}
private Node delete(Node node, int value) {
if (node == null) {
return null;
}
if (value < node.value) {
node.left = delete(node.left, value);
} else if (value > node.value) {
node.right = delete(node.right, value);
} else {
if (node.left == null) {
return node.right;
} else if (node.right == null) {
return node.left;
} else {
Node minNode = findMinNode(node.right);
node.value = minNode.value;
node.right = delete(node.right, minNode.value);
}
}
return node;
}
private Node findMinNode(Node node) {
while (node.left != null) {
node = node.left;
}
return node;
}
// 节点类
private class Node {
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
}
}
阅读全文