Skip to content

Commit 1f3ab93

Browse files
committed
2 parents bc63df5 + 6d771e6 commit 1f3ab93

File tree

2 files changed

+125
-0
lines changed

2 files changed

+125
-0
lines changed

Diff for: 4주차/김유경/레벨3__길_찾기_게임.js

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
function solution(nodeinfo) {
2+
let answer = [];
3+
4+
nodeinfo.map((x, i) => x.push(i + 1));
5+
//y값이 큰 순으로 정렬, 아니면 x값이 작은 순으로 정렬
6+
const sorted = nodeinfo.sort((a, b) => b[1] - a[1] || a[0] - b[0]);
7+
const tree = new Tree();
8+
9+
for (let i = 0; i < sorted.length; i++) {
10+
const [x, y, node] = sorted[i];
11+
tree.insert(node, x);
12+
}
13+
14+
tree.preOrder(tree.root);
15+
tree.postOrder(tree.root);
16+
17+
answer.push(tree.pre);
18+
answer.push(tree.post);
19+
20+
return answer;
21+
}
22+
23+
class Node {
24+
constructor(value, x) {
25+
this.value = value;
26+
this.left = null;
27+
this.right = null;
28+
this.x = x;
29+
}
30+
}
31+
32+
class Tree {
33+
constructor() {
34+
this.root = null;
35+
this.pre = [];
36+
this.post = [];
37+
}
38+
39+
insert(value, x) {
40+
if (this.root === null) {
41+
this.root = new Node(value, x);
42+
return;
43+
}
44+
const queue = [];
45+
queue.push(this.root);
46+
47+
while (queue.length > 0) {
48+
const currentNode = queue.shift();
49+
const newNode = new Node(value, x);
50+
51+
// 부모보다 현재의 새로은 node값의 x가 더 작다면 왼쪽으로
52+
if (currentNode.x > newNode.x) {
53+
if (currentNode.left === null) {
54+
currentNode.left = newNode;
55+
break;
56+
} else {
57+
queue.push(currentNode.left);
58+
}
59+
// 아니라면 오른쪽으로
60+
} else {
61+
if (currentNode.right === null) {
62+
currentNode.right = newNode;
63+
break;
64+
} else {
65+
queue.push(currentNode.right);
66+
}
67+
}
68+
}
69+
}
70+
71+
preOrder(node) {
72+
if (!node) {
73+
return;
74+
}
75+
this.pre.push(node.value);
76+
this.preOrder(node.left);
77+
this.preOrder(node.right);
78+
}
79+
80+
postOrder(node) {
81+
if (!node) {
82+
return;
83+
}
84+
this.postOrder(node.left);
85+
this.postOrder(node.right);
86+
this.post.push(node.value);
87+
}
88+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const fs = require("fs");
2+
const filePath =
3+
process.platform === "linux" ? "/dev/stdin" : `${__dirname}/input.txt`;
4+
let input = fs.readFileSync(filePath).toString().trim().split("\n");
5+
6+
const n = Number(input.shift());
7+
const arr = input.map((x) =>
8+
x
9+
.trim()
10+
.split(" ")
11+
.map((x) => +x)
12+
);
13+
14+
const graph = Array.from(Array(n + 1), () => []);
15+
const visited = Array(n + 1).fill(false);
16+
const parent = Array(n + 1).fill(0);
17+
18+
arr.forEach(([v, u]) => {
19+
graph[u].push(v);
20+
graph[v].push(u);
21+
});
22+
23+
dfs(1);
24+
25+
function dfs(i) {
26+
if (!visited[i]) {
27+
visited[i] = true;
28+
graph[i].forEach((e) => {
29+
if (!visited[e]) {
30+
parent[e] = i;
31+
dfs(e);
32+
}
33+
});
34+
}
35+
}
36+
37+
console.log(parent.slice(2).join("\n"));

0 commit comments

Comments
 (0)