function solution(nodeinfo) {
var answer = [[]];
function Node(x,y,value){
this.x = x
this.y = y
this.value = value
this.left = null
this.right = null
}
function Tree(head){
this.head = null;
this.append = (x,y,value) => {
const node = new Node(x,y,value)
if(!this.head){ // 빈 tree일 경우
this.head = node;
return;
}
let parent = this.head
while(true){
if(x > parent.x){
if(parent.right){
parent = parent.right;
}else{
parent.right = node;
break;
}
}else{
if(parent.left){
parent = parent.left;
}else{
parent.left = node;
break;
}
}
}
}
this.preorder = () => {
const nodes = []
const dfs = (node) => {
nodes.push(node.value)
node.left && dfs(node.left)
node.right && dfs(node.right)
}
dfs(this.head)
return nodes
}
this.postorder = () => {
const nodes = []
const dfs = (node) => {
node.left && dfs(node.left)
node.right && dfs(node.right)
nodes.push(node.value)
}
dfs(this.head)
return nodes;
}
}
const tree = new Tree()
nodeinfo.map((node,i) => ([node, i])).sort((b,a) => a[0][1] - b[0][1]).forEach(([node, index]) => {
const [x,y] = node
const value = index+1
tree.append(x,y,value)
})
return [tree.preorder(), tree.postorder()];
}
Level
프로그래머스 Lv3
Day
18일
kakao
2019 카카오 블라인드