์ ์์ํ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํ์ผ๋ก ํธ๋ฆฌ๋ฅผ ๋ง๋ค๊ณ , ํ์์ํ๋ฅผ ์ถ๋ ฅํ๋ฉด ๋๋ค.
ํ์ด ์์
1. ์ ๋ ฅ์ ๋ฐํ์ผ๋ก ํธ๋ฆฌ๋ฅผ ๊ตฌ์ฑ. (๋ ธ๋ ํด๋์ค๋ฅผ ํ์ฉ)
2. ๋ ธ๋ ํด๋์ค ๋ด๋ถ์ insert ํจ์ ์์ฑ.
insert ํจ์ : ์ ๋ ฅ๋ ๋ ธ๋์ ๊ฐ์ ํ์ฌ ๋ ธ๋ ๊ฐ๊ณผ ๋น๊ตํ์ฌ, ์ผ์ชฝ ํน์ ์ค๋ฅธ์ชฝ์ ๋ฌ์์ฃผ๋ ํจ์.
์ด๋ insert ํจ์์ ์ฌ๊ทํจ์๋ฅผ ์ ์ฉํด์ผ ํ๋ค.
- ํด๋น ์์น๊ฐ ๋น์ด์์ผ๋ฉด ํด๋น ์์น์ ๋ ธ๋๋ฅผ ๋ฌ์์ฃผ๊ณ ,
- ๋น์ด์์ง ์๋ค๋ฉด ํด๋น ์์น์ ์๋ ๋ ธ๋์ insertํจ์๋ฅผ ์ฌ๊ทํธ์ถ
์ฝ๋
package com.mincheolsong;
import java.io.*;
import java.util.*;
public class Main {
// BOJ 5639๋ฒ ์ด์ง ๊ฒ์ ํธ๋ฆฌ
static class Node{
int num;
Node left, right;
public Node(int num){
this.num = num;
}
public void insert(Node input){
if(this.num > input.num){ // ์ผ์ชฝ
if(this.left == null){ // ๋น์ด์์ผ๋ฉด ๋ฌ์์ฃผ๊ธฐ
this.left = input;
}else{ // ๋น์ด์์ง ์์ผ๋ฉด ์ฌ๊ทํธ์ถ
this.left.insert(input);
}
}else { // ์ค๋ฅธ์ชฝ
if(this.right == null){ // ๋น์ด์์ผ๋ฉด ๋ฌ์์ฃผ๊ธฐ
this.right = input;
}else{ // ๋น์ด์์ง ์์ผ๋ฉด ์ฌ๊ทํธ์ถ
this.right.insert(input);
}
}
}
}
static void solve(Node node){
if(node!=null){
solve(node.left);
solve(node.right);
System.out.println(node.num);
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Node root = new Node(Integer.parseInt(br.readLine()));
while(true){
String input = br.readLine();
if(input==null || input.equals("")) break;
int n = Integer.parseInt(input);
root.insert(new Node(n));
}
solve(root);
}
}
๋ฌธ์
์ด์ง ๊ฒ์ ํธ๋ฆฌ๋ ๋ค์๊ณผ ๊ฐ์ ์ธ ๊ฐ์ง ์กฐ๊ฑด์ ๋ง์กฑํ๋ ์ด์ง ํธ๋ฆฌ์ด๋ค.
- ๋ ธ๋์ ์ผ์ชฝ ์๋ธํธ๋ฆฌ์ ์๋ ๋ชจ๋ ๋ ธ๋์ ํค๋ ๋ ธ๋์ ํค๋ณด๋ค ์๋ค.
- ๋ ธ๋์ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ์ ์๋ ๋ชจ๋ ๋ ธ๋์ ํค๋ ๋ ธ๋์ ํค๋ณด๋ค ํฌ๋ค.
- ์ผ์ชฝ, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ ์ด์ง ๊ฒ์ ํธ๋ฆฌ์ด๋ค.
์ ์ ์ํ (๋ฃจํธ-์ผ์ชฝ-์ค๋ฅธ์ชฝ)์ ๋ฃจํธ๋ฅผ ๋ฐฉ๋ฌธํ๊ณ , ์ผ์ชฝ ์๋ธํธ๋ฆฌ, ์ค๋ฅธ์ชฝ ์๋ธ ํธ๋ฆฌ๋ฅผ ์์๋๋ก ๋ฐฉ๋ฌธํ๋ฉด์ ๋ ธ๋์ ํค๋ฅผ ์ถ๋ ฅํ๋ค. ํ์ ์ํ (์ผ์ชฝ-์ค๋ฅธ์ชฝ-๋ฃจํธ)๋ ์ผ์ชฝ ์๋ธํธ๋ฆฌ, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ, ๋ฃจํธ ๋ ธ๋ ์์๋๋ก ํค๋ฅผ ์ถ๋ ฅํ๋ค. ์๋ฅผ ๋ค์ด, ์์ ์ด์ง ๊ฒ์ ํธ๋ฆฌ์ ์ ์ ์ํ ๊ฒฐ๊ณผ๋ 50 30 24 5 28 45 98 52 60 ์ด๊ณ , ํ์ ์ํ ๊ฒฐ๊ณผ๋ 5 28 24 45 30 60 52 98 50 ์ด๋ค.
์ด์ง ๊ฒ์ ํธ๋ฆฌ๋ฅผ ์ ์ ์ํํ ๊ฒฐ๊ณผ๊ฐ ์ฃผ์ด์ก์ ๋, ์ด ํธ๋ฆฌ๋ฅผ ํ์ ์ํํ ๊ฒฐ๊ณผ๋ฅผ ๊ตฌํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
์ ๋ ฅ
ํธ๋ฆฌ๋ฅผ ์ ์ ์ํํ ๊ฒฐ๊ณผ๊ฐ ์ฃผ์ด์ง๋ค. ๋ ธ๋์ ๋ค์ด์๋ ํค์ ๊ฐ์ 106๋ณด๋ค ์์ ์์ ์ ์์ด๋ค. ๋ชจ๋ ๊ฐ์ ํ ์ค์ ํ๋์ฉ ์ฃผ์ด์ง๋ฉฐ, ๋ ธ๋์ ์๋ 10,000๊ฐ ์ดํ์ด๋ค. ๊ฐ์ ํค๋ฅผ ๊ฐ์ง๋ ๋ ธ๋๋ ์๋ค.
์ถ๋ ฅ
์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ง ์ด์ง ๊ฒ์ ํธ๋ฆฌ๋ฅผ ํ์ ์ํํ ๊ฒฐ๊ณผ๋ฅผ ํ ์ค์ ํ๋์ฉ ์ถ๋ ฅํ๋ค.
'๐์ฝ๋ฉํ ์คํธ:CodingTest' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์๋ก์ ์งํฉ ์๋ฃ๊ตฌ์กฐ (Union Find) (๋ฐฑ์ค 1043๋ฒ) (0) | 2024.01.03 |
---|---|
๋ค์ต์คํธ๋ผ (boj 12851 ์จ๋ฐ๊ผญ์ง2) (0) | 2024.01.02 |
๋ค์ต์คํธ๋ผ (๋ฐฑ์ค 13549 ์จ๋ฐ๊ผญ์ง 3) (1) | 2023.12.26 |
ํธ๋ฆฌ์ ์ง๋ฆ (๋ฐฑ์ค 1167๋ฒ) (2) | 2023.12.26 |
ํ๋ก์ด๋ ์์ ์๊ณ ๋ฆฌ์ฆ (0) | 2023.12.14 |