[프로그래머스] Lv3. 길 찾기 게임- JavaScript

이상돈·2023년 9월 7일
0
post-thumbnail

문제분류 : 코팅테스트 연습

난이도 : Level 3

출처 : 프로그래머스 - 길 찾기 게임

문제

제한사항

📌 내가 생각한 풀이

클래스를 이용하여 주어진 조건에 맞는 트리를 만들고, 전위 순회와 후위 순회를 하여 값을 출력하자.
let arr1 = [];
let arr2 = [];
class Tree{
    constructor([x,y], num){
        this.value = [x,y];
        this.left = null;
        this.right = null;
        this.num = num
    }
    pushNode([x,y], num){
        if(x > this.value[0]){
            if(this.right === null){
                this.right = new Tree([x,y],num);    
            }else{
                this.right.pushNode([x,y],num)
            }
        }else if(x < this.value[0]){
            if(this.left === null){
                this.left = new Tree([x,y],num);
            }else{
                this.left.pushNode([x,y],num)
            }
        }
    }
    frontCircuit(){
        arr1.push(this.num)
        if(this.left !== null){
            this.left.frontCircuit()
        }
        if(this.right !== null){
            this.right.frontCircuit()
        }
    }
    backCircuit(){
        if(this.left !== null){
            this.left.backCircuit()
        }
        if(this.right !== null){
            this.right.backCircuit();
        }
        arr2.push(this.num);
        
    }
    
}
let nodeNum = {}


function solution(nodeinfo) {
    var answer = [[]];
    nodeinfo.forEach((d,i)=>{
        nodeNum[d] = i+1;
    })
    nodeinfo.sort((a,b)=>{
        if(a[1] === b[1]){
            return a[0] - b[0]
        }else{
            return b[1] - a[1]
        }
    });
    let tree = new Tree(nodeinfo[0], nodeNum[nodeinfo[0]]);
    for(var i =1; i<nodeinfo.length; i++){
        tree.pushNode(nodeinfo[i], nodeNum[nodeinfo[i]]);
    }
    tree.frontCircuit()
    tree.backCircuit()
    let result =[];
    result.push(arr1)
    result.push(arr2)
    return (result)
}

📌 느낀점

이진 트리를 만들 때 배열을 사용하여 만드는 경우도 존재하였지만, 클래스를 사용하여 만들면 훨씬 직관적으로 만들 수 있다. 클래스를 자주 사용하자.

profile
사람들의 더 나은 삶을 위한 개발자

0개의 댓글