[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ธธ ์ฐพ๊ธฐ ๊ฒŒ์ž„ / ํŒŒ์ด์ฌ / ์ž๋ฃŒ๊ตฌ์กฐ(ํŠธ๋ฆฌ)
Problem Solving ๐Ÿ”ฅ/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ธธ ์ฐพ๊ธฐ ๊ฒŒ์ž„ / ํŒŒ์ด์ฌ / ์ž๋ฃŒ๊ตฌ์กฐ(ํŠธ๋ฆฌ)

https://programmers.co.kr/learn/courses/30/lessons/42892

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ธธ ์ฐพ๊ธฐ ๊ฒŒ์ž„

[[5,3],[11,5],[13,3],[3,5],[6,1],[1,3],[8,6],[7,2],[2,2]] [[7,4,6,9,1,8,5,2,3],[9,6,5,8,1,4,3,2,7]]

programmers.co.kr

ํ’€์ด

์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ ์ ˆํžˆ ์‚ฌ์šฉํ•˜๋Š”์ง€๋ฅผ ๋ฌป๋Š” ๋ฌธ์ œ์˜€๋˜ ๊ฒƒ ๊ฐ™๋‹ค.

์ด์ง„ํŠธ๋ฆฌ๋ฅผ ํ•œ ๋ฒˆ ๊ตฌํ˜„ํ•ด ๋ณธ ๊ฒฝํ—˜์ด ์žˆ์œผ๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€๋‹ค.

์šฐ์„  ๋†’์ด๋ณ„๋กœ ํ•œ ๋ฒˆ ์ •๋ ฌ์„ ํ•œ ๋‹ค์Œ์—, ์ด์ง„ํŠธ๋ฆฌ์— ๊ณ„์† ์ถ”๊ฐ€ํ•˜๋Š” ํ˜•์‹์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค.

๋”ฑํžˆ ์„ค๋ช…์ด ํ•„์š”์—†์„ ๋“ฏ ํ•˜๋‹ค..

import heapq as h
import sys
sys.setrecursionlimit(100000)
answer = [[], []]

class Node:
    right_child = None
    left_child = None
    x = None
    y = None
    idx = None

    def __init__(self, x, y, idx):
        self.x = x
        self.y = y
        self.idx = idx

    def insert(self, newNode):
        nx, ny = newNode.x, newNode.y
        # ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๊ฐ€์•ผํ•จ
        if nx > self.x:
            if self.right_child == None:
                self.right_child = newNode
            else:
                self.right_child.insert(newNode)
        # ์™ผ์ชฝ์œผ๋กœ ๊ฐ€์•ผํ•จ
        else:
            if self.left_child == None:
                self.left_child = newNode
            else:
                self.left_child.insert(newNode)

    def preorder(self):
        global answer
        answer[0].append(self.idx)
        if self.left_child != None:
            self.left_child.preorder()
        if self.right_child != None:
            self.right_child.preorder()

    def postorder(self):
        global answer
        if self.left_child != None:
            self.left_child.postorder()
        if self.right_child != None:
            self.right_child.postorder()
        answer[1].append(self.idx) 

def solution(nodeinfo):
    global answer
    # idx ์ˆœ์„œ ๋„ฃ๊ธฐ
    for i in range(len(nodeinfo)):
        nodeinfo[i].append(i+1)
    # ๋†’์ด์— ๋”ฐ๋ผ ์ •๋ ฌ
    nodeinfo = sorted(nodeinfo, key=lambda n: (-n[1], n[0]) )
    # ๊ฐ€์žฅ ์œ„์— ์žˆ๋Š” ๋…ธ๋“œ
    rootNode = None

    for x, y, idx in nodeinfo:
        newNode = Node(x, y, idx)
        if rootNode == None:
            rootNode = newNode
        else:
            rootNode.insert(newNode)
    rootNode.preorder()
    rootNode.postorder()
    return answer