Java代码实现构造一颗三叉链表表示的二叉树,实现采用先根、中根、后根、层次算法遍历二叉树,输出二叉树结点值
时间: 2023-12-24 22:06:06 浏览: 73
以下是Java代码实现构造一颗三叉链表表示的二叉树,实现采用先根、中根、后根、层次算法遍历二叉树,输出二叉树结点值的实现:
```java
// 三叉链表表示的二叉树结点类
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode parent;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
this.parent = null;
}
}
// 三叉链表表示的二叉树类
class BinaryTree {
TreeNode root;
// 构造函数
public BinaryTree() {
root = null;
}
// 插入结点
public void insert(int val) {
TreeNode newNode = new TreeNode(val);
if (root == null) {
root = newNode;
} else {
TreeNode current = root;
while (true) {
if (val < current.val) {
if (current.left == null) {
current.left = newNode;
newNode.parent = current;
break;
} else {
current = current.left;
}
} else {
if (current.right == null) {
current.right = newNode;
newNode.parent = current;
break;
} else {
current = current.right;
}
}
}
}
}
// 先根遍历
public void preOrder(TreeNode node) {
if (node != null) {
System.out.print(node.val + " ");
preOrder(node.left);
preOrder(node.right);
}
}
// 中根遍历
public void inOrder(TreeNode node) {
if (node != null) {
inOrder(node.left);
System.out.print(node.val + " ");
inOrder(node.right);
}
}
// 后根遍历
public void postOrder(TreeNode node) {
if (node != null) {
postOrder(node.left);
postOrder(node.right);
System.out.print(node.val + " ");
}
}
// 层次遍历
public void levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if (root != null) {
queue.offer(root);
}
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
System.out.print(node.val + " ");
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
// 测试函数
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.insert(6);
tree.insert(3);
tree.insert(8);
tree.insert(2);
tree.insert(5);
tree.insert(7);
tree.insert(9);
System.out.print("先根遍历:");
tree.preOrder(tree.root);
System.out.println();
System.out.print("中根遍历:");
tree.inOrder(tree.root);
System.out.println();
System.out.print("后根遍历:");
tree.postOrder(tree.root);
System.out.println();
System.out.print("层次遍历:");
tree.levelOrder(tree.root);
System.out.println();
}
}
```
输出结果为:
```
先根遍历:6 3 2 5 8 7 9
中根遍历:2 3 5 6 7 8 9
后根遍历:2 5 3 7 9 8 6
层次遍历:6 3 8 2 5 7 9
```
阅读全文