
문제풀이
문제해석
나의 코드
function solution(nodeinfo) { var answer = [[],[]]; // 노드를 만들고 순회하는거 class Node{ constructor(index,value){ this.index=index; this.value=value; this.right=null; this.left= null; } }
class BinaryTree{
constructor() {
this.root = null;
}
insertNode(node,root){
if(root.value> node.value){
//오른쪽이 큰거 왼쪽이 작은거라고 가정
if(root.left==null) root.left= node;
else{
this.insertNode(node,root.left);
}
}
else{
if(root.right==null) root.right=node;
else{
this.insertNode(node,root.right);
}
}
}
insert(index,value){
const new_node= new Node(index,value);
if(this.root==null) this.root= new_node;
else{
this.insertNode(new_node,this.root)
}
}
// 전위순회
preorder (root){
if(root==null) return ;
answer[0].push(root.index);
this.preorder(root.left);
this.preorder(root.right)
}
postorder(root){
if(root==null) return ;
this.postorder(root.left);
this.postorder(root.right);
answer[1].push(root.index);
}
}
//이렇게 연결하는거 다함 이제 노드를 만들어보자
nodeinfo=nodeinfo.map((El,index)=> [El[0],El[1],index+1])
nodeinfo.sort((a,b)=>{
if(a[1]==b[1]) return a[0]-b[0];
else{
return b[1]-a[1]
}
})
const start_node_tree= new BinaryTree();
nodeinfo.forEach((el,index)=>{
start_node_tree.insert(el[2],el[0])
})
start_node_tree.preorder(start_node_tree.root);
start_node_tree.postorder(start_node_tree.root);
//console.dir(start_node_tree, { depth: null });
return answer;
}