已知先序中序求后序Java
时间: 2023-11-29 14:05:49 浏览: 106
可以使用递归的方式来实现先序和中序求后序,具体实现代码如下:
```java
public class Tree {
private static class Node {
private char value;
private Node left;
private Node right;
public Node(char value) {
this.value = value;
}
}
public static String preInToPost(String preOrder, String inOrder) {
if (preOrder == null || inOrder == null || preOrder.length() != inOrder.length()) {
return null;
}
Node root = preInToPost(preOrder.toCharArray(), 0, preOrder.length() - 1, inOrder.toCharArray(), 0, inOrder.length() - 1);
StringBuilder sb = new StringBuilder();
postOrder(root, sb);
return sb.toString();
}
private static Node preInToPost(char[] preOrder, int preStart, int preEnd, char[] inOrder, int inStart, int inEnd) {
if (preStart > preEnd) {
return null;
}
Node root = new Node(preOrder[preStart]);
int index = findIndex(inOrder, inStart, inEnd, preOrder[preStart]);
int leftSize = index - inStart;
root.left = preInToPost(preOrder, preStart + 1, preStart + leftSize, inOrder, inStart, index - 1);
root.right = preInToPost(preOrder, preStart + leftSize + 1, preEnd, inOrder, index + 1, inEnd);
return root;
}
private static void postOrder(Node root, StringBuilder sb) {
if (root == null) {
return;
}
postOrder(root.left, sb);
postOrder(root.right, sb);
sb.append(root.value);
}
private static int findIndex(char[] arr, int start, int end, char target) {
for (int i = start; i <= end; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String preOrder = "ABDCEGF";
String inOrder = "DBAEGCF";
String postOrder = preInToPost(preOrder, inOrder);
System.out.println(postOrder); // DCBGEFA
}
}
```
该代码中使用了一个内部类 `Node` 表示二叉树的节点,`preInToPost` 方法用于递归构建二叉树,`postOrder` 方法用于递归遍历二叉树并输出后序遍历序列,`findIndex` 方法用于查找中序遍历序列中某个元素的位置。最后在 `main` 方法中调用 `preInToPost` 方法并输出结果。
阅读全文