본문 바로가기
HackerRank

findProfession

by Doromi 2024. 4. 8.
728x90
반응형
이진 트리의 특정 레벨과 위치에 있는 사람의 직업을 결정하는 문제입니다.

만약 레벨이 1인 경우, 해당 사람의 직업은 "Engineer"입니다.
그렇지 않은 경우, 해당 사람의 직업은 부모의 직업에 따라 결정됩니다.
부모가 "Engineer"인 경우, 해당 사람의 위치에 따라 “Engineer” 또는 "Doctor"로 번갈아가며 결정됩니다.
부모가 "Doctor"인 경우, 해당 사람의 위치에 따라 직업이 반대로 결정됩니다 (짝수 위치는 “Engineer”, 홀수 위치는 “Doctor”).

 

string solution(int level, int pos) {
    return findProfession(level,pos);
}

string findProfession(int level,int pos){
    if(pos == 1) return "Engineer";
    
    int parentPos  = (pos+1)/2;
    string parent = findProfession(level-1,parentPos);
    if(parent == "Engineer"){
        return (pos%2 == 0) ? "Doctor":"Engineer";
    }
    else{
        return (pos%2 == 0) ? "Engineer":"Doctor";
    }
}
parentPos는 현재 위치 pos의 부모 노드의 위치를 나타냅니다. 이진 트리에서 부모 노드의 위치는 (pos + 1) / 2로 계산됩니다. 예를 들어, pos가 3인 경우, (3 + 1) / 2는 2가 되어 부모 노드의 위치가 2라는 의미입니다.
728x90
반응형

'HackerRank' 카테고리의 다른 글

isTreeSymmetric  (0) 2024.04.05
hasPathWithGivenSum  (0) 2024.04.02
Top Competitors(SQL)  (0) 2023.10.20
The Report(SQL)  (0) 2023.10.19
Average Population of Each Continent(SQL)  (0) 2023.10.19