https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem
Tree: Height of a Binary Tree | HackerRank
Given a binary tree, print its height.
www.hackerrank.com
<문제>


input으로 첫번째 줄에 node의 개수 n을 입력받고, 두번째 줄에 n개만큼의 node를 입력받는다.
output으로 tree의 height를 출력한다.
<코드>
int getHeight(struct node* root) {
int i= 0;
struct node* n = root;
while(n && (n->left != NULL || n->right!= NULL ) )
{
if (n->right != NULL)
{
n = n->right;
i++;
continue;
}
if (n->left != NULL)
{
n = n->left;
i++;
continue;
}
}
return i;
}
<코드 풀이>

while반복문을 이용해 struct node에 있는 left와 right가 NULL이 아닐 때까지 i값을 1씩 증가시키면서 tree의 height를 측정하였다. right와 left가 모두 NULL이면 i값을 리턴하여 문제를 풀 수 있었다.
<결과>

'c언어 스터디 > HackerRank' 카테고리의 다른 글
| [HackerRank] Subarray Division (0) | 2021.06.25 |
|---|---|
| [HackerRank] Breaking the Records (0) | 2021.05.28 |
| [HackerRank] Grading Students (0) | 2021.05.22 |
| [HackerRank] Sorting- Counting Sort 2 (0) | 2021.05.22 |
| [HackerRank] Sorting- Counting Sort 1 (0) | 2021.05.13 |