

Node class 안의 left Node right Node 를 구현하여 이진트리를 구현해 내었고
출력위치를 조정하여
전위, 중위, 후위 순회를 구현해 냈다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Node{
char value;
Node left;
Node right;
public Node(char value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
public class b1991 {
static int N;
static Node head = new Node('A',null,null);
public static void insertNode(Node temp, char root, char left, char right) {
if (temp.value == root) {
temp.left = (left == '.' ? null : new Node(left,null,null));
temp.right = (right == '.' ? null : new Node(right,null,null));
}
else {
if(temp.left != null)
insertNode(temp.left, root, left, right);
if(temp.right != null)
insertNode(temp.right, root, left, right);
}
}
public static void preOrder(Node node) {
if(node ==null) return;
System.out.print(node.value);
preOrder(node.left);
preOrder(node.right);
}
public static void inOrder(Node node) {
if(node ==null) return;
inOrder(node.left);
System.out.print(node.value);
inOrder(node.right);
}
public static void postOrder(Node node) {
if(node ==null) return;
postOrder(node.left);
postOrder(node.right);
System.out.print(node.value);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
for(int i = 0 ; i < N ; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
char value = st.nextToken().charAt(0);
char left = st.nextToken().charAt(0);
char right = st.nextToken().charAt(0);
insertNode(head,value,left,right);
}
preOrder(head);
System.out.println();
inOrder(head);
System.out.println();
postOrder(head);
System.out.println();
}
}
'Algorithm & Data Structures > BOJ' 카테고리의 다른 글
1865. 웜홀 (Java) (1) | 2024.01.02 |
---|---|
1918. 후위 표기식 (Java) (0) | 2024.01.01 |
2096. 내려가기 (Java) (0) | 2023.12.18 |
2448. 별찍기 - 11 (Java) (0) | 2023.12.13 |
14938. 서강그라운드 (Java) (1) | 2023.11.29 |