hdu1710—二叉树遍历java
时间: 2023-11-24 09:52:35 浏览: 157
用java实现二叉树的创建和遍历.doc
以下是HDU1710—二叉树遍历的Java代码实现:
```java
import java.util.Scanner;
public class Main {
static int[] preOrder;
static int[] inOrder;
static int[] postOrder;
static int n;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); while (sc.hasNext()) {
n = sc.nextInt();
preOrder = new int[n];
inOrder = new int[n];
postOrder = new int[n];
for (int i = 0; i < n; i++) {
preOrder[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
inOrder[i] = sc.nextInt();
}
getPostOrder(0, n - 1, 0, n - 1);
for (int i = 0; i < n; i++) {
System.out.print(postOrder[i] + " ");
}
System.out.println();
}
}
private static void getPostOrder(int preL, int preR, int inL, int inR) {
if (preL > preR) {
return;
}
int root = preOrder[preL];
int k = 0;
for (k = inL; k <= inR; k++) {
if (inOrder[k] == root) {
break;
}
}
int numLeft = k - inL;
getPostOrder(preL + 1, preL + numLeft, inL, k - 1);
getPostOrder(preL + numLeft + 1, preR, k + 1, inR);
postOrder[n - 1 - (inR - k)] = root;
}
}
```
阅读全文