Java现在键盘输入一颗二叉树的先序遍历序列和中序遍历序列,试着找出它的后序遍历序列。
时间: 2023-12-27 11:03:52 浏览: 91
JavaScript数据结构与算法之二叉树遍历算法详解【先序、中序、后序】
可以通过递归的方式来实现二叉树的构建和遍历,下面是Java代码实现:
```java
import java.util.Scanner;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class BinaryTree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入二叉树的先序遍历序列:");
String preOrderStr = scanner.nextLine();
System.out.print("请输入二叉树的中序遍历序列:");
String inOrderStr = scanner.nextLine();
int[] preOrder = new int[preOrderStr.length()];
for (int i = 0; i < preOrderStr.length(); i++) {
preOrder[i] = Integer.parseInt(preOrderStr.substring(i, i + 1));
}
int[] inOrder = new int[inOrderStr.length()];
for (int i = 0; i < inOrderStr.length(); i++) {
inOrder[i] = Integer.parseInt(inOrderStr.substring(i, i + 1));
}
TreeNode root = buildTree(preOrder, inOrder);
System.out.print("后序遍历序列为:");
postOrderTraversal(root);
}
private static TreeNode buildTree(int[] preOrder, int[] inOrder) {
return buildTreeHelper(preOrder, 0, preOrder.length - 1, inOrder, 0, inOrder.length - 1);
}
private static TreeNode buildTreeHelper(int[] preOrder, int preStart, int preEnd, int[] inOrder, int inStart, int inEnd) {
if (preStart > preEnd) {
return null;
}
int rootVal = preOrder[preStart];
TreeNode root = new TreeNode(rootVal);
int rootIndex = 0;
for (int i = inStart; i <= inEnd; i++) {
if (inOrder[i] == rootVal) {
rootIndex = i;
break;
}
}
int leftSize = rootIndex - inStart;
root.left = buildTreeHelper(preOrder, preStart + 1, preStart + leftSize, inOrder, inStart, rootIndex - 1);
root.right = buildTreeHelper(preOrder, preStart + leftSize + 1, preEnd, inOrder, rootIndex + 1, inEnd);
return root;
}
private static void postOrderTraversal(TreeNode root) {
if (root == null) {
return;
}
postOrderTraversal(root.left);
postOrderTraversal(root.right);
System.out.print(root.val);
}
}
```
输入格式为:
```
请输入二叉树的先序遍历序列:12473568
请输入二叉树的中序遍历序列:47215386
```
输出格式为:
```
后序遍历序列为:74258631
```
其中,`buildTree`方法用于构建二叉树,`postOrderTraversal`方法用于进行后序遍历。
阅读全文