Java中如何使用函数实现二叉搜索树?
发布时间:2023-09-25 00:24:34
要在Java中实现二叉搜索树(BST),首先需要定义一个BST的节点类。节点类应该包含一个值和左右子节点的引用。
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
接下来,我们需要实现一个BST的主类。主类应该包含以下方法:
- 插入节点方法(insert):将一个新的值插入到BST中的正确位置。
- 查找节点方法(search):根据给定的值在BST中查找对应的的节点。
- 删除节点方法(delete):从BST中删除指定的节点。
- 中序遍历方法(inorderTraversal):按顺序输出BST中的所有节点的值。
下面是一个实现了上述方法的BST主类的示例代码:
public class BST {
private TreeNode root;
public BST() {
root = null;
}
public void insert(int val) {
root = insertNode(root, val);
}
private TreeNode insertNode(TreeNode root, int val) {
if (root == null) {
root = new TreeNode(val);
return root;
}
if (val < root.val) {
root.left = insertNode(root.left, val);
} else if (val > root.val) {
root.right = insertNode(root.right, val);
}
return root;
}
public TreeNode search(int val) {
return searchNode(root, val);
}
private TreeNode searchNode(TreeNode root, int val) {
if (root == null || root.val == val) {
return root;
}
if (val < root.val) {
return searchNode(root.left, val);
}
return searchNode(root.right, val);
}
public void delete(int val) {
root = deleteNode(root, val);
}
private TreeNode deleteNode(TreeNode root, int val) {
if (root == null) {
return root;
}
if (val < root.val) {
root.left = deleteNode(root.left, val);
} else if (val > root.val) {
root.right = deleteNode(root.right, val);
} else {
if (root.left == null) {
return root.right;
} else if (root.right == null) {
return root.left;
}
root.val = getMinValue(root.right);
root.right = deleteNode(root.right, root.val);
}
return root;
}
private int getMinValue(TreeNode root) {
int minValue = root.val;
while (root.left != null) {
minValue = root.left.val;
root = root.left;
}
return minValue;
}
public void inorderTraversal() {
inorder(root);
}
private void inorder(TreeNode root) {
if (root != null) {
inorder(root.left);
System.out.print(root.val + " ");
inorder(root.right);
}
}
}
现在我们可以创建一个BST对象,然后使用insert方法插入新的节点,使用search方法查找指定的节点,使用delete方法删除指定的节点,使用inorderTraversal方法输出BST的所有节点值。以下是一个使用BST类的示例:
public class Main {
public static void main(String[] args) {
BST bst = new BST();
bst.insert(5);
bst.insert(3);
bst.insert(7);
bst.insert(2);
bst.insert(4);
bst.inorderTraversal(); // 输出:2 3 4 5 7
TreeNode result = bst.search(3);
System.out.println("
" + result.val); // 输出:3
bst.delete(5);
bst.inorderTraversal(); // 输出:2 3 4 7
}
}
以上是用Java实现二叉搜索树的基本方法。实际上,还可以实现其他功能,如前序遍历、后序遍历、最小值和最大值的查找等等。
