java用三叉链表构造二叉树
时间: 2024-03-06 20:43:49 浏览: 81
基于二叉链表的二叉树实现
5星 · 资源好评率100%
在Java中,可以使用三叉链表来构造二叉树。下面是一个示例代码,演示了如何使用三叉链表实现二叉树的基本操作。
```java
// 定义二叉树节点类
class BTNode {
int data;
BTNode left;
BTNode right;
BTNode parent;
public BTNode(int data) {
this.data = data;
this.left = null;
this.right = null;
this.parent = null;
}
}
// 构造二叉树的类
class BinaryTree {
BTNode root;
public BinaryTree() {
this.root = null;
}
// 插入节点
public void insert(int data) {
BTNode newNode = new BTNode(data);
if (root == null) {
root = newNode;
} else {
BTNode current = root;
BTNode parent;
while (true) {
parent = current;
if (data < current.data) {
current = current.left;
if (current == null) {
parent.left = newNode;
newNode.parent = parent;
return;
}
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
newNode.parent = parent;
return;
}
}
}
}
}
// 其他二叉树操作方法...
// 复制二叉树
public void copyTree(BTNode dstTreeRoot, BTNode srcTreeRoot) {
if (srcTreeRoot == null) {
dstTreeRoot = null;
} else {
dstTreeRoot = new BTNode(srcTreeRoot.data);
if (srcTreeRoot.left != null) {
copyTree(dstTreeRoot.left, srcTreeRoot.left);
dstTreeRoot.left.parent = dstTreeRoot;
}
if (srcTreeRoot.right != null) {
copyTree(dstTreeRoot.right, srcTreeRoot.right);
dstTreeRoot.right.parent = dstTreeRoot;
}
}
}
}
// 示例代码
public class Main {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(2);
tree.insert(4);
tree.insert(6);
tree.insert(8);
// 复制二叉树
BinaryTree copiedTree = new BinaryTree();
copiedTree.copyTree(copiedTree.root, tree.root);
// 其他操作...
}
}
```
阅读全文