https://www.acmicpc.net/problem/1991
이진트리를 만들고 전위순회, 중위순회, 후위순회를 하면 되는 코드입니다.
코드입니다.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Node root = new Node();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
root.index = "A";
int N = sc.nextInt();
for(int i=0;i<N;i++) {
String parent = sc.next();
String left = sc.next();
String right = sc.next();
addNode(root, parent, left, right);
}
preorder(root);
System.out.println();
midorder(root);
System.out.println();
postorder(root);
}
static void addNode(Node temp, String parent, String leftchild, String rightchild) {
if(temp.index.equals(parent)) {
if(!leftchild.equals(".")) {
temp.left = new Node(leftchild);
}
if(!rightchild.equals(".")) {
temp.right = new Node(rightchild);
}
}else {
if(temp.left != null) addNode(temp.left, parent, leftchild, rightchild);
if(temp.right != null) addNode(temp.right, parent, leftchild, rightchild);
}
return ;
}
static void preorder(Node start) {
if(start == null) return ;
System.out.print(start.index);
preorder(start.left);
preorder(start.right);
}
static void midorder(Node start) {
if(start == null) return ;
midorder(start.left);
System.out.print(start.index);
midorder(start.right);
}
static void postorder(Node start) {
if(start == null) return ;
postorder(start.left);
postorder(start.right);
System.out.print(start.index);
}
static class Node{
String index;
Node left;
Node right;
Node(){
}
Node(String index){
this.index = index;
}
}
}
'알고리즘 > Tree' 카테고리의 다른 글
[백준] 1967 트리의 지름 - 골드4, DFS + 트리(Tree) 자바 (0) | 2023.01.13 |
---|---|
[백준] 나무 위의 빗물 - 골드5, 트리(Tree) (0) | 2023.01.12 |
[백준] 트리 - 골드5, 트리(Tree) (0) | 2023.01.12 |
[백준] 단절점과 단절선 - 실버1, 트리(Tree) (0) | 2023.01.12 |
[백준] 11725 트리의 부모 찾기 - 트리(Tree) + DFS(깊이우선탐색) JAVA (0) | 2023.01.11 |