-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBOJ1991.java
More file actions
109 lines (86 loc) · 3.05 KB
/
BOJ1991.java
File metadata and controls
109 lines (86 loc) · 3.05 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ1991 {
static int n;
static Tree tree;
private static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
tree = new Tree();
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
char parent = st.nextToken().charAt(0);
char left = st.nextToken().charAt(0);
char right = st.nextToken().charAt(0);
tree.addNode(parent, left, right);
}
}
public static void main(String[] args) throws IOException {
input();
process();
}
private static void process() {
tree.printPreorder(tree.root);
System.out.println();
tree.printInorder(tree.root);
System.out.println();
tree.printPostorder(tree.root);
System.out.println();
}
static class Node {
char data;
Node leftChild;
Node rightChild;
public Node(char data){
this.data = data;
}
}
static class Tree {
Node root = null;
void addNode(char data, char leftChildData, char rightChildData){
if(root == null){
root = new Node(data);
root.leftChild = (leftChildData != '.') ? new Node(leftChildData) : null;
root.rightChild= (rightChildData != '.') ? new Node(rightChildData) : null;
}else{
findAndAddNode(this.root, data, leftChildData, rightChildData);
}
}
void findAndAddNode(Node node, char targetData, char leftChildData, char rightChildData){
if(node.data == targetData){
node.leftChild = (leftChildData != '.') ? new Node(leftChildData) : null;
node.rightChild= (rightChildData != '.') ? new Node(rightChildData) : null;
return;
}
if(node.leftChild != null){
findAndAddNode(node.leftChild, targetData, leftChildData, rightChildData);
}
if(node.rightChild != null){
findAndAddNode(node.rightChild, targetData, leftChildData, rightChildData);
}
}
void printPreorder(Node node){
if(node == null)
return;
System.out.print(node.data);
printPreorder(node.leftChild);
printPreorder(node.rightChild);
}
void printInorder(Node node){
if(node == null)
return;
printInorder(node.leftChild);
System.out.print(node.data);
printInorder(node.rightChild);
}
void printPostorder(Node node){
if(node == null)
return;
printPostorder(node.leftChild);
printPostorder(node.rightChild);
System.out.print(node.data);
}
}
}