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
'Problem Solving ๐ฅ > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] ์งํ ์ด๋ / ํ์ด์ฌ / MST(์ต์์ ์ฅํธ๋ฆฌ) (0) | 2021.02.14 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค] ํ๋ ธ์ด์ ํ / ํ์ด์ฌ (0) | 2021.02.12 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์คํ ์์ด / ํ์ด์ฌ (0) | 2021.02.12 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์ ํ ๋ฒ์ค / ํ์ด์ฌ / (์๋ฎฌ๋ ์ด์ ) (0) | 2021.01.31 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์ซ์ ๊ฒ์ / ํ์ด์ฌ / (์ ๋ ฌ, ์ด์ง ํ์) (0) | 2021.01.30 |