-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSB_42892.java
More file actions
90 lines (76 loc) ยท 2.77 KB
/
SB_42892.java
File metadata and controls
90 lines (76 loc) ยท 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SB_42892 {
static int N;
static Node[] tree;
private static void postOrder(Node node, List<Integer> post) {
if (node==null) return; // ๋ฆฌํ๋
ธ๋์์ ๋ ์ด์ ๋
ธ๋๊ฐ ์์ผ๋ฉด ๋ฆฌํด
postOrder(node.left, post);
postOrder(node.right, post);
post.add(node.n);
}
private static void preOrder(Node node, List<Integer> pre) {
if (node==null) return; // ๋ฆฌํ๋
ธ๋์์ ๋ ์ด์ ๋
ธ๋๊ฐ ์์ผ๋ฉด ๋ฆฌํด
pre.add(node.n);
preOrder(node.left, pre);
preOrder(node.right, pre);
}
private static void setChild(Node parent, Node child) {
if (child.x < parent.x){ // ์ผ์ชฝ ๋
ธ๋ ์ ํ๊ธฐ
if (parent.left==null) parent.left = child; // ์ผ์ชฝ ์๋ฆฌ ๋น์์ผ๋ฉด child๋ก ์ค์
else setChild(parent.left, child); // ๋น์ด์์ง ์์ผ๋ฉด ์ผ์ชฝ ๋
ธ๋๋ฅผ ๋ถ๋ชจ๋ก ํ๋ child ์ค์
}else { // ์ค๋ฅธ์ชฝ ๋
ธ๋ ์ ํ๊ธฐ
if (parent.right==null) parent.right = child;
else setChild(parent.right, child);
}
}
public static int[][] solution(int[][] nodeinfo) {
N = nodeinfo.length;
tree = new Node[N];
// ๋
ธ๋ ๊ฐ ํฌํจํด์ ํธ๋ฆฌ ๋ฐฐ์ด ์ฌ๊ตฌ์ฑ
for (int i = 0; i < N; i++) {
int[] n = nodeinfo[i];
tree[i] = new Node(n[0], n[1], i + 1);
}
Arrays.sort(tree);
// ๊ฐ ๋
ธ๋์ ์ค๋ฅธ์ชฝ, ์ผ์ชฝ ๊ฐ ์ค์
Node root = tree[0];
for (int i = 1; i < N; i++) {
setChild(root, tree[i]);
}
// ์ ์ ์ํ
List<Integer> pre = new ArrayList<>();
preOrder(root, pre);
// ํ์ ์ํ
List<Integer> post = new ArrayList<>();
postOrder(root, post);
int[][] ans = new int[2][N];
ans[0] = pre.stream().mapToInt(i->i).toArray();
ans[1] = post.stream().mapToInt(i -> i).toArray();
return ans;
}
static class Node implements Comparable<Node>{
int x, y, n;
Node left = null;
Node right = null;
public Node(int x, int y, int n) {
this.x = x;
this.y = y;
this.n = n;
}
@Override
public int compareTo(Node o) {
if (o.y-this.y==0) return this.x-o.x;
return o.y-this.y;
}
@Override
public String toString() {
return "Node{" +
"x=" + x +
", y=" + y +
", n=" + n +
'}';
}
}
}