https://www.acmicpc.net/problem/5639
노드를 정의한뒤에 이진검색트리 조건대로 노드를 추가하도록 하였고
후위 순회 재귀함수로 출력하도록 하였다
노드를 사용하지 않고 풀어보려고 하였지만 잘 안됨
Binary Tree의 시간복잡도가 어떻게 되나요? Binary Search Tree의 경우 노드가 n개 일 경우 평균적으로 O(log(n)) 이고 최악일 경우(단일 경사트리일 경우) O(n)이다
import java.io.*;
class Node
{
int val;
Node left;
Node right;
public Node() {
}
public Node(int val) {
this.val = val;
}
public void add(Node newNode)
{
if(newNode.val < this.val)
{
if(null != left)
left.add(newNode);
else
left = newNode;
}
else
{
if(null != right)
right.add(newNode);
else
right = newNode;
}
}
}
public class Main
{
static int rootVal;
static Node root;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException
{
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
rootVal = Integer.parseInt(br.readLine());
root = new Node(rootVal);
while (true) {
int temp = Integer.parseInt(br.readLine());
root.add(new Node(temp));
}
}
catch(Exception e)
{
}
recur_PostOrder(root);
System.out.println(sb);
}
public static void recur_PostOrder(Node node)
{
Node left = node.left;
if(left != null)
{
recur_PostOrder(left);
}
Node right = node.right;
if(right != null)
{
recur_PostOrder(right);
}
sb.append(node.val+"\n");
}
}