본문 바로가기

c언어 스터디/HackerRank

[HackerRank] Tree- Level Order Traversal

Tree: Level Order Traversal | HackerRank

 

Tree: Level Order Traversal | HackerRank

Level order traversal of a binary tree.

www.hackerrank.com

 

<문제>

입력된 트리를 level order로 출력하는 문제이다.

 

<코드>

void levelOrder( struct node *root) {
    struct node *queue[500];
    int front = 0, count = 0;
    queue[front + count] = root;
    count++;
        
    while (count-->0){
            struct node *temp = queue[front++];
            printf("%d ", temp->data);

            if (temp->left){
                    queue[front + count++] = temp->left;
            }
            if (temp->right){
                    queue[front + count++] = temp->right;
            }

        }

}

 

<코드 풀이>

먼저 크기가 500인 queue를 생성하고 front=0, count=0으로 초기화하였다.

문제는 level order이므로 tree에 left가 있으면 left를 먼저 출력하고, right가 있으면 다음으로 출력해야한다.

levelorder()함수는 while반복문을 이용해 풀 수 있었다.

while반복문은 포인터 temp가 queue[front]를 가리키고 있다. 만약 temp에 left가 있다면 queue에 추가하고, right가 있다면 queue에 추가하고 count를 1씩 증가시킨다. 이 반복문은 count-->0일 동안 반복되고, 0이 되면 종료된다.

 

<결과>