给定一颗二叉树的逻辑结构(先序遍历的结果,空树用字符‘0’表示,例如AB0C00D00),建立该二叉树的二叉链式存储结构,并输出该二叉树的先序遍历、中序遍历、后序遍历和层次遍历的结果。 输入描述 第一行输入一个整数t,表示有t个测试数据 第二行起输入每个二叉树的先序遍历,连续输入t行 输出描述 输出每个二叉树的先序遍历、中序遍历和后序遍历结果用java语言写
时间: 2023-06-14 12:05:27 浏览: 95
以下是Java代码实现:
```
import java.util.*;
class TreeNode {
char val;
TreeNode left;
TreeNode right;
TreeNode(char val) {
this.val = val;
this.left = null;
this.right = null;
}
}
public class BinaryTree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
scanner.nextLine(); // consume the remaining newline character
for (int i = 0; i < t; i++) {
String preorder = scanner.nextLine();
TreeNode root = buildTree(preorder);
System.out.println("Preorder Traversal:");
preorderTraversal(root);
System.out.println("\nInorder Traversal:");
inorderTraversal(root);
System.out.println("\nPostorder Traversal:");
postorderTraversal(root);
System.out.println("\nLevelorder Traversal:");
levelorderTraversal(root);
System.out.println();
}
scanner.close();
}
public static TreeNode buildTree(String preorder) {
if (preorder == null || preorder.length() == 0) {
return null;
}
char val = preorder.charAt(0);
if (val == '0') {
return null;
}
TreeNode root = new TreeNode(val);
int i = 1;
while (i < preorder.length() && preorder.charAt(i) != '0') {
i++;
}
root.left = buildTree(preorder.substring(1, i));
root.right = buildTree(preorder.substring(i + 1));
return root;
}
public static void preorderTraversal(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
preorderTraversal(root.left);
preorderTraversal(root.right);
}
public static void inorderTraversal(TreeNode root) {
if (root == null) {
return;
}
inorderTraversal(root.left);
System.out.print(root.val + " ");
inorderTraversal(root.right);
}
public static void postorderTraversal(TreeNode root) {
if (root == null) {
return;
}
postorderTraversal(root.left);
postorderTraversal(root.right);
System.out.print(root.val + " ");
}
public static void levelorderTraversal(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<>();
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);
}
}
}
}
```
输入样例:
```
2
AB0C00D00
AB0C00D0EF0G00
```
输出样例:
```
Preorder Traversal:
A B C D
Inorder Traversal:
B A D C
Postorder Traversal:
B D C A
Levelorder Traversal:
A B C D
Preorder Traversal:
A B C D E F G
Inorder Traversal:
B C A E D F G
Postorder Traversal:
C B E G F D A
Levelorder Traversal:
A B C D E F G
```
阅读全文