백준 5639

旅人·2023년 3월 11일
0

문제


문제 상단에 이진트리의 조건에 따르면

루트 노드보다 작은 노드들은 모두 루트 노드 왼쪽 서브 트리

루트 노드보다 큰 노드들은 모두 루트 노드 오른쪽 서브트리에 위치한다

따라서 전위 순위로 입력 받은 첫 노드를 루트 노드에 놓고

후에 이어지는 입력들은 루트 노드부터 각 노드와 크기 비교를 통해

배치하면 전체 트리의 상태를 알 수 있다.


package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class P5639 {
	static class Node {
		int num;
		Node left;
		Node right;
		Node(int num) {
			this.num = num;
		}
        
        /*
		Node(int num, Node left, Node right) {
			this.num = num;
			this.left = left;
			this.right = right;
		}
        */
        
		void insertNode(int n) {
			if(n < this.num) {
				if(this.left == null) {
					this.left = new Node(n);
				} else { // 왼쪽 자식 노드가 있다면 다시 그것과 비교
					this.left.insertNode(n);
				}
			} else {
				if(this.right == null) {
					this.right = new Node(n);
				} else { // 오른쪽 자식 노드가 있다면 다시 그것과 비교
					this.right.insertNode(n);
				}
			}
		}
	}

	public static void main(String[] args) throws IOException  {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // 루트 노드 --> 가장 처음 입력받은 값
		Node root = new Node(Integer.parseInt(br.readLine()));
		String input;
		while(true) {
			input = br.readLine();
            // 입력 길이에 제한이 없다
			if(input == null || input.equals("")) {
				break;
			}
			root.insertNode(Integer.parseInt(input));
		}
		postOrder(root);
	}
	
	private static void postOrder(Node node) {
		if(node == null) {
			return;
		}
		postOrder(node.left);
		postOrder(node.right);
		System.out.println(node.num);
	}
	
	

}

참고 : https://girawhale.tistory.com/59

profile
一期一会

0개의 댓글