-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5639.java
More file actions
79 lines (76 loc) · 1.87 KB
/
Copy path5639.java
File metadata and controls
79 lines (76 loc) · 1.87 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
// https://www.acmicpc.net/problem/5639
// 이진 검색 트리
import java.util.*;
import java.lang.*;
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
MyTree myTree = new MyTree();
String input = scan.readLine();
while(input != null){
myTree.add(Integer.parseInt(input));
input = scan.readLine();
}
System.out.println(myTree.toString());
}
}
class MyTree{
Node head;
public MyTree(){
head = null;
}
public void add(int n){
if(head == null){
head = new Node(n);
return;
}
Node cur = head;
while(true){
if(cur.value > n){
if(cur.left == null){
cur.setLeft(n);
return;
}
else cur = cur.left;
}
else if(cur.value < n){
if(cur.right == null){
cur.setRight(n);
return;
}
else cur = cur.right;
}
}
}
StringBuilder sb;
public String toString(){
sb = new StringBuilder();
dfs(head);
return sb.toString();
}
public void dfs(Node cur){
if(cur == null) return;
if(cur.left == null && cur.right == null){
sb.append(cur.value).append('\n');
return;
}
dfs(cur.left);
dfs(cur.right);
sb.append(cur.value).append('\n');
}
}
class Node{
int value;
Node left, right;
public Node(int value){
this.value = value;
left = right = null;
}
public void setLeft(int n){
left = new Node(n);
}
public void setRight(int n){
right = new Node(n);
}
}