문제 원본 : https://www.acmicpc.net/problem/5639
5639번: 이진 검색 트리
트리를 전위 순회한 결과가 주어진다. 노드에 들어있는 키의 값은 106보다 작은 양의 정수이다. 모든 값은 한 줄에 하나씩 주어지며, 노드의 수는 10,000개 이하이다. 같은 키를 가지는 노드는 없다
www.acmicpc.net
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BST bst = new BST();
String str = "";
while((str = br.readLine()) != null) {
if (str.length() == 0) {
break;
}
bst.insert(Integer.valueOf(str));
}
bst.postOrder(bst.root);
bw.write(bst.builder.toString());
bw.close();
br.close();
}
static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
static class BST {
public Node root;
public StringBuilder builder = new StringBuilder();
public void insert(int value) {
if (root == null) {
root = new Node(value);
} else {
Node tmp = root;
Node parent;
while(true) {
parent = tmp;
if (value == parent.value) {
return;
} else if (value < parent.value) {
tmp = parent.left;
if (tmp == null) {
parent.left = new Node(value);
return;
}
} else {
tmp = parent.right;
if (tmp == null) {
parent.right = new Node(value);
return;
}
}
}
}
}
public void postOrder(Node node) {
if (node == null) {
return;
}
postOrder(node.left);
postOrder(node.right);
builder.append(node.value).append("\n");
}
}
}
'알고리즘 > BOJ' 카테고리의 다른 글
| [BOJ] 2206. 벽 부수고 이동하기 (0) | 2022.02.27 |
|---|---|
| [BOJ] 1406. 에디터 (0) | 2022.02.26 |
| [BOJ] 14003. 가장 긴 증가하는 부분 수열 5 (0) | 2022.02.24 |
| [BOJ] 11054. 가장 긴 바이토닉 부분 수열 (0) | 2022.02.23 |
| [BOJ] 1992. 쿼드트리 (0) | 2022.02.22 |