java代码实现创建一棵二叉链表表示的二叉树中,实现以广义表表示构造二叉树,并采用先根、中根、后根、层次算法输出二叉树字符
时间: 2023-12-24 12:05:54 浏览: 55
以下是Java代码实现:
```java
import java.util.LinkedList;
public class BinaryTree {
// 二叉树结点类
private class Node {
char val;
Node left;
Node right;
Node(char val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// 根结点
private Node root;
// 以广义表表示构造二叉树
public void createBinaryTree(String str) {
LinkedList<Node> stack = new LinkedList<>();
Node node = null;
boolean flag = false; // 标记是否为左子树
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '(') {
stack.push(node);
flag = true; // 下一个结点为左子树
} else if (c == ')') {
stack.pop(); // 弹出栈顶结点
} else if (c == ',') {
flag = false; // 下一个结点为右子树
} else {
node = new Node(c); // 创建新结点
if (root == null) {
root = node; // 第一个结点为根结点
} else {
if (flag) {
stack.peek().left = node; // 左子树
} else {
stack.peek().right = node; // 右子树
}
}
}
}
}
// 先根遍历
public void preOrder(Node node) {
if (node != null) {
System.out.print(node.val + " ");
preOrder(node.left);
preOrder(node.right);
}
}
// 中根遍历
public void inOrder(Node node) {
if (node != null) {
inOrder(node.left);
System.out.print(node.val + " ");
inOrder(node.right);
}
}
// 后根遍历
public void postOrder(Node node) {
if (node != null) {
postOrder(node.left);
postOrder(node.right);
System.out.print(node.val + " ");
}
}
// 层次遍历
public void levelOrder(Node root) {
LinkedList<Node> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
Node 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();
String str = "A(B(D,E(G,)),C(,F))";
tree.createBinaryTree(str);
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);
}
}
```
输出结果:
```
先根遍历:A B D E G C F
中根遍历:D B G E A C F
后根遍历:D G E B F C A
层次遍历:A B C D E F G
```
阅读全文