AcWing 1589. 构建二叉搜索树-java-二叉树的数组表示+先序遍历+层序遍历
原题链接
中等
作者:
Astarion
,
2021-03-11 09:17:15
,
所有人可见
,
阅读 493
import java.io.*;
import java.util.Arrays;
class Main {
static InputStreamReader isr = new InputStreamReader(System.in);
static BufferedReader in = new BufferedReader(isr);
static OutputStreamWriter osw = new OutputStreamWriter(System.out);
static BufferedWriter out = new BufferedWriter(osw);
static String[] strs;
static final int N = 110;
static int n;
//存储二叉树结点编号对应的子结点编号、值
static int[] lc = new int[N];
static int[] rc = new int[N];
static int[] v = new int[N];
static boolean[] flag = new boolean[N];
//插入顺序
static int idx;
static int[] order = new int[N];
static {
Arrays.fill(lc, -1);
Arrays.fill(rc, -1);
}
static int head, tail, cnt;
static int[] queue = new int[N];
static void levelOrder() throws IOException {
queue[tail++] = 0;
while (head < tail) {
int x = queue[head++];
cnt++;
out.write(v[x]+" ");
if (cnt == n) return;
if (lc[x] != -1) queue[tail++] = lc[x];
if (rc[x] != -1) queue[tail++] = rc[x];
}
}
//先序遍历确定插入顺序
static void preOrder(int i) {
if (lc[i] != -1 && !flag[lc[i]]) preOrder(lc[i]);
order[cnt++] = i;
flag[i] = true;
if (rc[i] != -1 && !flag[rc[i]]) preOrder(rc[i]);
}
public static void main(String[] args) throws IOException {
n = Integer.parseInt(in.readLine());
for (int i = 0; i < n; i++) {
strs = in.readLine().split(" ");
lc[i] = Integer.parseInt(strs[0]);
rc[i] = Integer.parseInt(strs[1]);
flag[i] = false;
}
strs = in.readLine().split(" ");
int[] temp = new int[n];
for (int i = 0; i < n; i++) temp[i] = Integer.parseInt(strs[i]);
Arrays.sort(temp);
preOrder(0);
for (int i = 0; i < n; i++) v[order[i]] = temp[i];
levelOrder();
in.close();
isr.close();
out.flush();
out.close();
osw.close();
}
}