-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathJY_42892.java
More file actions
94 lines (83 loc) ยท 2.58 KB
/
JY_42892.java
File metadata and controls
94 lines (83 loc) ยท 2.58 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
91
92
93
94
import java.util.*;
class Solution {
static List<Node> nList;
static int N;
static boolean[] visited;
static class Node {
int x, y, num;
Node left, right;
public Node(int x, int y, int num) {
this.x = x;
this.y = y;
this.num = num;
}
@Override
public String toString() {
return this.num+": ["+this.x+","+this.y+"]";
}
}
static List<Node> nodeList;
static List<Integer> preOrderList;
static List<Integer> postOrderList;
public int[][] solution(int[][] nodeinfo) {
N = nodeinfo.length;
int[][] answer = new int[2][N];
// ๋
ธ๋ ๋ฆฌ์คํธ ์์ฑ ๋ฐ ์ ๋ ฌ
nodeList = new ArrayList<>();
for (int i = 0; i < N; i++) {
nodeList.add(new Node(nodeinfo[i][0], nodeinfo[i][1], i + 1));
}
// Y ๊ฐ ๊ธฐ์ค ๋ด๋ฆผ์ฐจ์, X ๊ฐ ๊ธฐ์ค ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
nodeList.sort((o1, o2) -> o2.y == o1.y ? o1.x - o2.x : o2.y - o1.y);
// ํธ๋ฆฌ ๋ง๋ค๊ธฐ
Node root = nodeList.get(0);
for (int i = 1; i < nodeList.size(); i++) {
insert(root, nodeList.get(i));
}
// ์ ์ ์ํ
preOrderList = new ArrayList<>();
postOrderList = new ArrayList<>();
preOrder(root);
postOrder(root);
// ๊ฒฐ๊ณผ ์ถ๋ ฅ
for(int i=0; i<N; i++) {
answer[0][i] = preOrderList.get(i);
answer[1][i] = postOrderList.get(i);
}
// System.out.println("Pre-order: " + preOrderList);
// System.out.println("Post-order: " + postOrderList);
return answer;
}
public static void insert(Node parent, Node child) {
// ๋ถ๋ชจ์ x๊ฐ์ด ์์๋ณด๋ค ํฌ๋ค๋ฉด -> ์ผ์ชฝ ์์
if (child.x < parent.x) {
if (parent.left == null) {
parent.left = child;
} else {
insert(parent.left, child);
}
}
// ๋ถ๋ชจ์ x๊ฐ์ด ์์๋ณด๋ค ์๋ค๋ฉด -> ์ค๋ฅธ์ชฝ ์์
else {
if (parent.right == null) {
parent.right = child;
} else {
insert(parent.right, child);
}
}
}
// ์ ์ ์ํ : ๋ฃจ->์ผ->์ค
private static void preOrder(Node node) {
if (node == null) return;
preOrderList.add(node.num);
preOrder(node.left);
preOrder(node.right);
}
// ํ์ ์ํ : ์ผ->์ค->๋ฃจ
private static void postOrder(Node node) {
if (node == null) return;
postOrder(node.left);
postOrder(node.right);
postOrderList.add(node.num);
}
}