AcWing 1592. 反转二叉树-java-O(n)
原题链接
中等
作者:
Astarion
,
2021-03-08 21:02:37
,
所有人可见
,
阅读 351
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 char non = '-';
static int n, root;
static int[] lc = new int[11];
static int[] rc = new int[11];
static int[] p = new int[11];
static {
Arrays.fill(lc, -1);
Arrays.fill(rc, -1);
Arrays.fill(p, -1);
}
static void levelOrder() throws IOException {
int[] queue = new int[11];
int head = 0, tail = 0;
queue[tail++] = root;
while (tail > head) {
int e = queue[head++];
out.write(String.format("%d ",e));
if (lc[e] != -1) queue[tail++] = lc[e];
if (rc[e] != -1) queue[tail++] = rc[e];
}
}
static void inOrder(int e) throws IOException {
if (lc[e] != -1) inOrder(lc[e]);
out.write(String.format("%d ",e));
if (rc[e] != -1) inOrder(rc[e]);
}
public static void main(String[] args) throws IOException {
n = Integer.parseInt(in.readLine());
String[] strs;
for (int i = 0; i < n; i++) {
strs = in.readLine().split(" ");
int l = (strs[0].charAt(0) == non) ? -1 : Integer.parseInt(strs[0]);
int r = (strs[1].charAt(0) == non) ? -1 : Integer.parseInt(strs[1]);
lc[i] = l;
rc[i] = r;
if (l != -1) p[l] = i;
if (r != -1) p[r] = i;
}
//翻转
for (int i = 0; i < n; i++) {
int temp = lc[i];
lc[i] = rc[i];
rc[i] = temp;
}
//找根节点
for (int i = 0; i < n; i++) {
if (p[i] == -1) {
root = i;
break;
}
}
levelOrder();
out.write('\n');
inOrder(root);
in.close();
isr.close();
out.flush();
out.close();
osw.close();
}
}