
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
public static class Node {
public int key;
public Node left;
public Node right;
Node(int k) {
key = k;
left = null;
right = null;
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
Node root = null;
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
int key = Integer.parseInt(line);
root = InsertNode(root, key);
}
print(root);
bw.close();
}
public static void print(Node root) throws IOException {
if (root.left != null) {
print(root.left);
}
if (root.right != null) {
print(root.right);
}
bw.write(root.key + "\n");
}
public static Node InsertNode(Node root, int key) {
if (root == null) {
return new Node(key);
}
if (root.key > key) {
root.left = InsertNode(root.left, key);
} else if (root.key < key) {
root.right = InsertNode(root.right, key);
}
return root;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 9935번: 문자열 폭발 (0) | 2025.05.09 |
|---|---|
| [JAVA-자바] 9663번: N-Queen (0) | 2025.05.09 |
| [JAVA-자바] 2448번: 별 찍기 - 11 (0) | 2025.05.05 |
| [JAVA-자바] 1987번: 알파벳 (0) | 2025.05.03 |
| [JAVA-자바] 1967번: 트리의 지름 (0) | 2025.05.03 |