MESSAGE
[JAVA] 백준 1991번 트리 순회
OTHER THINGS/STUDY STH

[HAVE TO DO]

STUDYING : JAVA


문제링크 : https://www.acmicpc.net/problem/1991

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	
	static int N;
	static Node[] tree;

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		N = Integer.parseInt(st.nextToken());
		
		tree = new Node[N];
		
		for (int i = 0; i < N; i++) {
			tree[i] = new Node((char)('A' + i));
		}
		
		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(br.readLine());
			char root = st.nextToken().charAt(0);
			char left = st.nextToken().charAt(0);
			char right = st.nextToken().charAt(0);
			
			if(left != '.') tree[(root - '0') - 17].setLeft(tree[(left - '0') - 17]);
			if(right != '.') tree[(root - '0') - 17].setRight(tree[(right - '0') - 17]);
		}
		
		preorder(tree[0]);
		System.out.print("\n");
		inorder(tree[0]);
		System.out.print("\n");
		postorder(tree[0]);
		
		br.close();
	}
	
	static void preorder(Node root) {
		if(root != null) {
			System.out.print(root.getData());
			preorder(root.getLeft());
			preorder(root.getRight());
		}
	}
	
	static void inorder(Node root) {
		if(root != null) {
			inorder(root.getLeft());
			System.out.print(root.getData());
			inorder(root.getRight());
		}
	}
	
	static void postorder(Node root) {
		if(root != null) {
			postorder(root.getLeft());
			postorder(root.getRight());
			System.out.print(root.getData());
		}
	}
	

}

class Node{
	private char data;
	private Node left;
	private Node right;
	
	public Node(char data) {
		this.data = data;
	}

	public char getData() {
		return data;
	}
	
	public void setData(char data) {
		this.data = data;
	}
	
	public Node getLeft() {
		return left;
	}
	
	public void setLeft(Node left) {
		this.left = left;
	}
	
	public Node getRight() {
		return right;
	}
	
	public void setRight(Node right) {
		this.right = right;
	}

	@Override
	public String toString() {
		return "Node [data=" + data + ", left=" + left + ", right=" + right + "]";
	}
	
}

Node를 배열로 받아 트리를 구현 후 각 트리에 left와 right를 세팅함

대문자 A를 숫자로 바꾸면 17이기 때문에 left right 세팅 때 -17을 해줌

 

 

'OTHER THINGS > STUDY STH' 카테고리의 다른 글

[JAVA] 백준 2042번 구간 합 구하기  (0) 2020.09.03
[JAVA] 백준 2014번 소수의 곱  (0) 2020.08.29
[JAVA] 백준 15686번 치킨 배달  (0) 2020.08.21
[JAVA] 백준 1103번 게임  (0) 2020.08.20
[JAVA] 백준 2580번 스도쿠  (0) 2020.08.20