알고리즘/백준 등

[백준] 이진검색트리

컵라면만두세트 2021. 5. 18. 00:51
package Solution;

import java.util.Scanner;

public class 이진검색트리 {
	
	/*
	 * Node라는구조체를 만들어준다.
	 * */
	
	
	public static class Node{
		Node left;
		Node right;
		int val;
		public Node(int v) {
			this.val = v;
		}
	}
	static int arr[] = new int[10001];
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt(); //50
		// root 
		Node root = new Node(N); //50
		while(sc.hasNext()) {
			try {				
				N = sc.nextInt(); //30
				//50 ,30
				root = insertNode(root, N);
			} catch (Exception e) {
				break;
			}
		}
		postOrder(root);
	}
	private static void postOrder(Node node) {
		if(node != null) {
			postOrder(node.left);
			postOrder(node.right);
			System.out.println(node.val);
		}
		
	}
	private static Node insertNode(Node node, int N) {
		Node current = null;
		if(node == null) {
			return new Node(N); //30
		}
		//50>30
		//50
		//30
		if(node.val>N) {
			current = insertNode(node.left, N); //30
			node.left = current;
		}else {
			current = insertNode(node.right,N);
			node.right = current;
		}
		return node;
	}

}

'알고리즘 > 백준 등' 카테고리의 다른 글

[백준] 요세푸스 문제  (0) 2021.06.11
[백준] 유기농배추  (0) 2021.06.09
[백준] 치킨배달  (0) 2021.05.09
[백준] 경로찾기  (0) 2021.05.09
[백준] 꽃길  (0) 2021.05.09