문제 설명


길 찾기 게임

전무로 승진한 라이언은 기분이 너무 좋아 프렌즈를 이끌고 특별 휴가를 가기로 했다.
내친김에 여행 계획까지 구상하던 라이언은 재미있는 게임을 생각해냈고 역시 전무로 승진할만한 인재라고 스스로에게 감탄했다.

라이언이 구상한(그리고 아마도 라이언만 즐거울만한) 게임은, 카카오 프렌즈를 두 팀으로 나누고, 각 팀이 같은 곳을 다른 순서로 방문하도록 해서 먼저 순회를 마친 팀이 승리하는 것이다.

그냥 지도를 주고 게임을 시작하면 재미가 덜해지므로, 라이언은 방문할 곳의 2차원 좌표 값을 구하고 각 장소를 이진트리의 노드가 되도록 구성한 후, 순회 방법을 힌트로 주어 각 팀이 스스로 경로를 찾도록 할 계획이다.

라이언은 아래와 같은 특별한 규칙으로 트리 노드들을 구성한다.

  • 트리를 구성하는 모든 노드의 x, y 좌표 값은 정수이다.
  • 모든 노드는 서로 다른 x값을 가진다.
  • 같은 레벨(level)에 있는 노드는 같은 y 좌표를 가진다.
  • 자식 노드의 y 값은 항상 부모 노드보다 작다.
  • 임의의 노드 V의 왼쪽 서브 트리(left subtree)에 있는 모든 노드의 x값은 V의 x값보다 작다.
  • 임의의 노드 V의 오른쪽 서브 트리(right subtree)에 있는 모든 노드의 x값은 V의 x값보다 크다.

아래 예시를 확인해보자.

라이언의 규칙에 맞게 이진트리의 노드만 좌표 평면에 그리면 다음과 같다. (이진트리의 각 노드에는 1부터 N까지 순서대로 번호가 붙어있다.)

이제, 노드를 잇는 간선(edge)을 모두 그리면 아래와 같은 모양이 된다.

위 이진트리에서 전위 순회(preorder), 후위 순회(postorder)를 한 결과는 다음과 같고, 이것은 각 팀이 방문해야 할 순서를 의미한다.

  • 전위 순회 : 7, 4, 6, 9, 1, 8, 5, 2, 3
  • 후위 순회 : 9, 6, 5, 8, 1, 4, 3, 2, 7

다행히 두 팀 모두 머리를 모아 분석한 끝에 라이언의 의도를 간신히 알아차렸다.

그러나 여전히 문제는 남아있다. 노드의 수가 예시처럼 적다면 쉽게 해결할 수 있겠지만, 예상대로 라이언은 그렇게 할 생각이 전혀 없었다.

이제 당신이 나설 때가 되었다.

곤경에 빠진 카카오 프렌즈를 위해 이진트리를 구성하는 노드들의 좌표가 담긴 배열 nodeinfo가 매개변수로 주어질 때,
노드들로 구성된 이진트리를 전위 순회, 후위 순회한 결과를 2차원 배열에 순서대로 담아 return 하도록 solution 함수를 완성하자.

제한사항

  • nodeinfo는 이진트리를 구성하는 각 노드의 좌표가 1번 노드부터 순서대로 들어있는 2차원 배열이다.
    • nodeinfo의 길이는 1 이상 10,000 이하이다.
    • nodeinfo[i] 는 i + 1번 노드의 좌표이며, [x축 좌표, y축 좌표] 순으로 들어있다.
    • 모든 노드의 좌표 값은 0 이상 100,000 이하인 정수이다.
    • 트리의 깊이가 1,000 이하인 경우만 입력으로 주어진다.
    • 모든 노드의 좌표는 문제에 주어진 규칙을 따르며, 잘못된 노드 위치가 주어지는 경우는 없다.

 

접근 방법


 제가 해결한 방법은 재귀함수를 통해 매개변수로 자식노드가 존재할 수 있는 x의 범위를 주었으며, 자식노드가 될 수 있는 후보를 선택하여 매개변수로 주어진 x의 범위안에 있는지 확인하며 트리를 구성하는 것입니다.

 

 왼쪽의 경계 값을 start, 오른쪽의 경계 값을 end, 현재 노드의 x좌표를 now_x라 가정합니다.

위의 그림에서 루트노드의 경우 start = -1 < now_x = 8 < end = 100001을 만족하므로 문제가 없습니다. 

이 상태에서 자식노드를 찾아 재귀함수를 진행하는 방법은 5가지의 순서로 구분지을 수 있습니다.

 

1. leftchild를 찾는 방법은 자신보다 y가 낮은 것 중에 가장 큰 y를 찾습니다. 

 

2. 1에서 찾은 y의 값을 갖는 것중 now_x보다 작은 x의 값을 가지면서 가장 큰 x를 갖는 노드가 후보가 될 수 있습니다.

이 때 찾아낸 후보 노드가 start ~ now_x사이의 x값을 가지고 있다면 그 후보 노드가 leftchild가 됩니다.

 

3. 2에서 leftchild를 찾았다면 end를 now_x로 변경하고, now = leftchild로 하여 재귀함수를 진행 시킵니다.

 

4. rightchild는 1에서 찾은 y의 값을 갖는 것중 now_x보다 큰 x의 값을 가지면서 가장 작은 x를 갖는 노드가 후보가 될 수 있습니다. 이 때 찾아낸 후보 노드가 now_x ~ end사이의 x값을 가지고 있다면 그 후보 노드가 rightchild가 됩니다.

 

5. 4에서 rightchild를 찾았다면 start를 now_x로 변경하고, now = rightchild로 하여 재귀함수를 진행시킵니다.

 

 

위의 방식을 진행시키기 이전에 문제에서 데이터를 전처리하여 treeinfo라는 벡터에 저장하였습니다.

typedef struct info{
    int x, num;
};

vector<info> treeinfo[100001];

treeinfo는 위와 같은 자료형을 가지며 treeinfo[y] = {x, 노드번호}를 의미합니다.

 

treeinfo는 높이에 따른 x와 노드번호를 가지며 x를 기준으로 오름차순으로 정렬하였습니다.

int init(vector<vector<int>> &nodeinfo){
   
    int maxh = -1;
    
    for(int i=0;i<nodeinfo.size();i++){
        treeinfo[nodeinfo[i][1]].push_back({nodeinfo[i][0], i+1});
        maxh = max(maxh, nodeinfo[i][1]);
    }
    for(int i=0;i<100001;i++)
        sort(treeinfo[i].begin(), treeinfo[i].end(), comp);
    
    return maxh;
}

maxh는 가장 상단의 노드의 y값이며 이를 구한 이유는 루트노드를 알아내기 위함입니다.

 

 

여기까지 이해가 되었다면 위에 설명한 1~5의 순서에 대해 소스코드로 설명하겠습니다. 

void makeTree(int start, int end, int now, vector<vector<int>> &nodeinfo){
    
    int now_x = nodeinfo[now - 1][0];
    int now_y = nodeinfo[now - 1][1];
    int next_y = findNextHeight(now_y); //1번 과정
    
    if(next_y < 0)
        return;
    
    int leftidx = findLeft(now_x, next_y);  //2번 과정
    int rightidx = findRight(now_x, next_y); //4번 과정
    
    if(start < treeinfo[next_y][leftidx].x && treeinfo[next_y][leftidx].x < now_x){ //3번 과정
        tree[now].left = treeinfo[next_y][leftidx].num; //leftchild연결
        makeTree(start, now_x, tree[now].left, nodeinfo);
    }    
    if(now_x < treeinfo[next_y][rightidx].x && treeinfo[next_y][rightidx].x < end){ //5번 과정
        tree[now].right = treeinfo[next_y][rightidx].num; //rightchild연결
        makeTree(now_x, end, tree[now].right, nodeinfo);
    }    
}

 

1번 과정에서 사용한 findNextHeight는 자신보다 높이가 작으면서 가장 큰 높이를 반환합니다.

//자신의 높이에서 1씩 내려가며 노드가 존재하는지 확인
int findNextHeight(int now){
    
    while(--now >= 0)
        if(treeinfo[now].size() > 0)
            break;
    return now;
}

 

2번과 4번 과정은 이분탐색을 응용하여 함수를 만들었습니다.

int findLeft(int val, int y){
    
    int start = 0;
    int end = treeinfo[y].size() - 1;
    
    while(start <= end){
        int mid = (start + end) / 2;
        if(treeinfo[y][mid].x >= val)
            end = mid - 1;
        else
            start = mid + 1;
    }
    return end = (end == -1) ? 0 : end;
}

int findRight(int val, int y){
    
    int start = 0;
    int end = treeinfo[y].size() - 1;
    
    while(start < end){
        int mid = (start + end) / 2;
        if(treeinfo[y][mid].x < val)
            start = mid + 1;
        else
            end = mid;
    }
    return end;
}

 

 1~5의 과정을 완료했다면 트리가 인접 리스트의 형태로 구성되었을 것입니다. 그렇다면 마지막으로 전위순회와 후위순회를 하여 정답을 구할 수 있습니다.

 

소스 코드


#include <string>
#include <algorithm>
#include <vector>

using namespace std;

typedef struct info{
    int x, num;
};
typedef struct child{
    int left, right;
};

vector<info> treeinfo[100001];
child tree[10001];

bool comp(info &a, info &b){
    return a.x < b.x;
}

int init(vector<vector<int>> &nodeinfo){
   
    int maxh = -1;
    
    for(int i=0;i<nodeinfo.size();i++){
        treeinfo[nodeinfo[i][1]].push_back({nodeinfo[i][0], i+1});
        maxh = max(maxh, nodeinfo[i][1]);
    }
    for(int i=0;i<100001;i++)
        sort(treeinfo[i].begin(), treeinfo[i].end(), comp);
    
    return maxh;
}

int findNextHeight(int now){
    
    while(--now >= 0)
        if(treeinfo[now].size() > 0)
            break;
    return now;
}

int findRight(int val, int y){
    
    int start = 0;
    int end = treeinfo[y].size() - 1;
    
    while(start < end){
        int mid = (start + end) / 2;
        if(treeinfo[y][mid].x < val)
            start = mid + 1;
        else
            end = mid;
    }
    return end;
}

int findLeft(int val, int y){
    
    int start = 0;
    int end = treeinfo[y].size() - 1;
    
    while(start <= end){
        int mid = (start + end) / 2;
        if(treeinfo[y][mid].x >= val)
            end = mid - 1;
        else
            start = mid + 1;
    }
    return end = (end == -1) ? 0 : end;
}

void makeTree(int start, int end, int now, vector<vector<int>> &nodeinfo){
    
    int now_x = nodeinfo[now - 1][0];
    int now_y = nodeinfo[now - 1][1];
    int next_y = findNextHeight(now_y);
    
    if(next_y < 0)
        return;
    
    int leftidx = findLeft(now_x, next_y);
    int rightidx = findRight(now_x, next_y);
    
    if(start < treeinfo[next_y][leftidx].x && treeinfo[next_y][leftidx].x < now_x){
        tree[now].left = treeinfo[next_y][leftidx].num;
        makeTree(start, now_x, tree[now].left, nodeinfo);
    }
    if(now_x < treeinfo[next_y][rightidx].x && treeinfo[next_y][rightidx].x < end){
        tree[now].right = treeinfo[next_y][rightidx].num;
        makeTree(now_x, end, tree[now].right, nodeinfo);
    }        
}

void preorder(int now, vector<int> &v){
    
    v.push_back(now);
    if(tree[now].left != 0)
        preorder(tree[now].left, v);
    if(tree[now].right != 0)
        preorder(tree[now].right, v);
}

void postorder(int now, vector<int> &v){
    
    if(tree[now].left != 0)
        postorder(tree[now].left, v);
    if(tree[now].right != 0)
        postorder(tree[now].right, v);
    v.push_back(now);
}

vector<vector<int>> solution(vector<vector<int>> nodeinfo) {

    vector<vector<int>> answer;
    vector<int> pre_v, post_v;
    
    int maxh = init(nodeinfo);
    int root = treeinfo[maxh][0].num;
    
    makeTree(-1, 100001, root, nodeinfo);
    preorder(root, pre_v);
    postorder(root, post_v);
    
    answer.push_back(pre_v);
    answer.push_back(post_v);
    
    for(int i=0;i<pre_v.size();i++)
        cout << pre_v[i] << " ";
    
    return answer;
}

+ Recent posts