BOJ - 5639 - 이진 검색 트리

Updated:

import sys
sys.setrecursionlimit(20_000)

class Node:
    def __init__(self, val):
        self.val = val
        self.leftChild = None
        self.rightChild = None

    def print_tree(self):
        if self.leftChild: self.leftChild.print_tree()
        if self.rightChild: self.rightChild.print_tree()
        print(self.val)


class BST:
    def __init__(self):
        self.root = None

    def setRoot(self, val):
        self.root = Node(val)

    def insert(self, val):
        if (self.root is None):
            self.setRoot(val)
        else:
            self.insertNode(self.root, val)

    def insertNode(self, currentNode, val):
        if (val <= currentNode.val):
            if (currentNode.leftChild):
                self.insertNode(currentNode.leftChild, val)
            else:
                currentNode.leftChild = Node(val)
        elif (val > currentNode.val):
            if (currentNode.rightChild):
                self.insertNode(currentNode.rightChild, val)
            else:
                currentNode.rightChild = Node(val)

def solution():
    bst = BST()

    while True:
        try: bst.insert(int(input()))
        except: break

    bst.root.print_tree()

solution()

https://www.acmicpc.net/problem/5639

Categories:

Updated:

Leave a comment