用Java语言写一个根据二叉树的先序和中序遍历求后序遍历
时间: 2024-05-07 10:23:41 浏览: 54
通过先序遍历和中序遍历后的序列还原二叉树(实现方法)
以下是Java代码实现:
```java
public class BinaryTree {
static int preIndex = 0;
public static void main(String[] args) {
int[] preOrder = {1, 2, 4, 5, 3};
int[] inOrder = {4, 2, 5, 1, 3};
int[] postOrder = constructTree(preOrder, inOrder, 0, inOrder.length - 1);
System.out.print("后序遍历结果:");
for (int i = 0; i < postOrder.length; i++) {
System.out.print(postOrder[i] + " ");
}
}
public static int[] constructTree(int[] preOrder, int[] inOrder, int inStart, int inEnd) {
if (inStart > inEnd) {
return null;
}
int rootValue = preOrder[preIndex++];
int inIndex = search(inOrder, inStart, inEnd, rootValue);
int[] leftTree = constructTree(preOrder, inOrder, inStart, inIndex - 1);
int[] rightTree = constructTree(preOrder, inOrder, inIndex + 1, inEnd);
int[] postOrder = new int[inEnd - inStart + 1];
int postIndex = 0;
if (leftTree != null) {
for (int i = 0; i < leftTree.length; i++) {
postOrder[postIndex++] = leftTree[i];
}
}
if (rightTree != null) {
for (int i = 0; i < rightTree.length; i++) {
postOrder[postIndex++] = rightTree[i];
}
}
postOrder[postIndex++] = rootValue;
return postOrder;
}
public static int search(int[] inOrder, int inStart, int inEnd, int value) {
int i;
for (i = inStart; i <= inEnd; i++) {
if (inOrder[i] == value) {
return i;
}
}
return i;
}
}
```
输出结果:
```
后序遍历结果:4 5 2 3 1
```
阅读全文