Java代码实现构造一颗三叉链表表示的二叉树,实现插入结点,实现采用先根、中根、后根、层次算法遍历二叉树,输出二叉树结点值
时间: 2024-01-28 17:03:43 浏览: 69
以下是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 void insert(int val) {
TreeNode node = new TreeNode(val);
if (root == null) {
root = node;
} else {
TreeNode parent = null;
TreeNode current = root;
while (current != null) {
parent = current;
if (val < current.val) {
current = current.left;
} else {
current = current.right;
}
}
if (val < parent.val) {
parent.left = node;
node.parent = parent;
} else {
parent.right = node;
node.parent = parent;
}
}
}
// 先根遍历
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 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);
System.out.println("先根遍历:");
tree.preOrder(tree.root);
System.out.println();
System.out.println("中根遍历:");
tree.inOrder(tree.root);
System.out.println();
System.out.println("后根遍历:");
tree.postOrder(tree.root);
System.out.println();
System.out.println("层次遍历:");
tree.levelOrder(tree.root);
System.out.println();
}
}
```
输出结果为:
```
先根遍历:
5 3 2 4 7 6 8
中根遍历:
2 3 4 5 6 7 8
后根遍历:
2 4 3 6 8 7 5
层次遍历:
5 3 7 2 4 6 8
```
阅读全文