[BOJ] 1991: 트리순회 (JAVA)

2025. 2. 25. 13:44·코테/Algorithm
728x90
백준 1991: 트리순회 (실버1)

 

 

풀이

 

트리의 순회를 코드로 구현하는 문제다.

전위순회는 N-L-R / 중위순회는 L-N-R / 후위 순회는 L-R-N 순으로 순회한다.

(L = 왼쪽 자식, N = 뿌리 노드, R = 오른쪽 자식)

 

노드를 저장하는 배열의 순서는 char를 사용해서 -'A'를 해주며 순서를 저장해준다.

 

전체코드
import java.io.*;
import java.util.*;

public class Main{
	static class Node{
		char N;
		Node left;
		Node right;
		Node(char N){
			this.N = N;
			this.left = left;
			this.right = right;
		}
	}
	static Node[] tree;
	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int n = Integer.parseInt(br.readLine());
		tree = new Node[n+1];
		
		for(int i=0; i<n; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			
			char nodeValue = st.nextToken().charAt(0);
			char leftValue = st.nextToken().charAt(0);
			char rightValue = st.nextToken().charAt(0);
			
			if(tree[nodeValue - 'A'] == null) {
				tree[nodeValue - 'A'] = new Node(nodeValue);
			}
			if(leftValue != '.') {
				tree[leftValue - 'A'] = new Node(leftValue);
				tree[nodeValue - 'A'].left = tree[leftValue - 'A'];
			}
			if(rightValue != '.') {
				tree[rightValue - 'A'] = new Node(rightValue);
				tree[nodeValue - 'A'].right = tree[rightValue - 'A'];
			}
		}
		
		preOrder(tree[0]);
		System.out.println();
		inOrder(tree[0]);
		System.out.println();
		postOrder(tree[0]);
	}
	
	static void preOrder(Node node) {
		if(node == null) return;
		System.out.print(node.N);
		preOrder(node.left);
		preOrder(node.right);
	}
	
	static void inOrder(Node node) {
		if(node == null) return;
		inOrder(node.left);
		System.out.print(node.N);
		inOrder(node.right);
	}
	
	static void postOrder(Node node) {
		if(node == null) return;
		postOrder(node.left);
		postOrder(node.right);
		System.out.print(node.N);
	}
	
}
728x90

'코테 > Algorithm' 카테고리의 다른 글

[프로그래머스] 서울에서 김서방 찾기 (Python)  (0) 2025.04.14
[프로그래머스] 없는 숫자 더하기(Python)  (0) 2025.04.14
[BOJ] 2644: 촌수계산 (JAVA)  (2) 2025.01.31
[백준] 11723: 집합 (JAVA)  (1) 2025.01.29
[백준] 9205: 맥주 마시면서 걸어가기 (JAVA)  (1) 2025.01.24
'코테/Algorithm' 카테고리의 다른 글
  • [프로그래머스] 서울에서 김서방 찾기 (Python)
  • [프로그래머스] 없는 숫자 더하기(Python)
  • [BOJ] 2644: 촌수계산 (JAVA)
  • [백준] 11723: 집합 (JAVA)
DROPDEW
DROPDEW
💻 Developer | 기록하지 않으면 존재하지 않는다
  • DROPDEW
    제 2장 1막
    DROPDEW
  • 전체
    오늘
    어제
    • Dev (440)
      • App·Android (1)
      • BE (50)
        • HTTP 웹 기본 지식 (8)
        • 스프링 입문 - 코드로 배우는 스프링 부트, 웹 .. (12)
        • 스프링부트와 JPA 활용 (11)
        • 스프링부트 시큐리티 & JWT (0)
        • 실전 자바 기본, 중급 (1)
        • PHP (11)
      • FE·Client (23)
        • HTML (1)
        • React (19)
        • Unity (1)
      • Data (28)
        • AI (7)
        • Bigdata (6)
        • Database (1)
        • Python (0)
        • 빅데이터분석기사 (13)
      • Infra (1)
      • Activity (5)
        • Education (0)
        • Intern (0)
        • 리모트 인턴십 6기 (3)
        • 구름톤 유니브 4기 (0)
        • SW교육기부단 15기 (0)
        • SK AI Dream Camp (2)
      • CS (8)
      • 취준 (13)
        • 자격증 (4)
        • 인적성·NCS (6)
        • 코테·필기·면접 후기 (3)
      • 코테 (270)
        • Algorithm (222)
        • SQL (35)
        • 정리 (13)
      • 인사이트 (27)
        • 회고 (0)
        • 금융경제뉴스 (7)
        • 금융용어·지식 (2)
        • 북마크 (7)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자료구조
    너비우선탐색
    누적합
    정렬
    수학
    시뮬레이션
    티스토리챌린지
    이분탐색
    그래프탐색
    최단경로
    구현
    브루트포스 알고리즘
    다이나믹프로그래밍
    투포인터
    그리디알고리즘
    오블완
    매개변수탐색
    백준
    문자열
    그래프이론
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
DROPDEW
[BOJ] 1991: 트리순회 (JAVA)
상단으로

티스토리툴바