Java 实现二叉树的封装
时间: 2023-05-12 07:03:57 浏览: 209
java实现二叉树
可以使用面向对象的思想,将二叉树的节点定义为一个类,包含左右子节点和节点值等属性,然后再定义一个二叉树类,包含根节点和相关的操作方法,如插入节点、删除节点、查找节点等。以下是一个简单的 Java 二叉树实现的示例代码:
```
public class BinaryTreeNode {
public int value;
public BinaryTreeNode left;
public BinaryTreeNode right;
public BinaryTreeNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
public class BinaryTree {
public BinaryTreeNode root;
public BinaryTree() {
this.root = null;
}
public void insert(int value) {
if (root == null) {
root = new BinaryTreeNode(value);
return;
}
BinaryTreeNode current = root;
while (true) {
if (value < current.value) {
if (current.left == null) {
current.left = new BinaryTreeNode(value);
return;
}
current = current.left;
} else {
if (current.right == null) {
current.right = new BinaryTreeNode(value);
return;
}
current = current.right;
}
}
}
public boolean contains(int value) {
BinaryTreeNode current = root;
while (current != null) {
if (current.value == value) {
return true;
} else if (value < current.value) {
current = current.left;
} else {
current = current.right;
}
}
return false;
}
public void delete(int value) {
root = delete(root, value);
}
private BinaryTreeNode delete(BinaryTreeNode node, int value) {
if (node == null) {
return null;
}
if (value == node.value) {
if (node.left == null) {
return node.right;
} else if (node.right == null) {
return node.left;
} else {
BinaryTreeNode minNode = findMin(node.right);
node.value = minNode.value;
node.right = delete(node.right, minNode.value);
}
} else if (value < node.value) {
node.left = delete(node.left, value);
} else {
node.right = delete(node.right, value);
}
return node;
}
private BinaryTreeNode findMin(BinaryTreeNode node) {
while (node.left != null) {
node = node.left;
}
return node;
}
}
```
以上代码实现了二叉树的插入、查找和删除操作,可以通过创建 BinaryTree 对象来使用。
阅读全文