SQL 문제

[해커랭크_Medium] Binary Tree Nodes

빙수빈수 2023. 10. 11. 16:04

https://www.hackerrank.com/challenges/binary-search-tree-1/problem?isFullScreen=true 

 

Binary Tree Nodes | HackerRank

Write a query to find the node type of BST ordered by the value of the node.

www.hackerrank.com

[문제]

You are given a table, BST, containing two columns: N and P, where N represents the value of a node in Binary Tree, and P is the parent of N.

Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each

 

node:

  • Root: If node is root node.
  • Leaf: If node is leaf node.
  • Inner: If node is neither root nor leaf node.

 

[코드]

select n,
    case 
        when p is null then 'Root'  
        when n not in (select distinct p from BST where p is not null) then 'Leaf'
        else 'Inner'
    end 
from BST
order by n;

 

[코드]

 이번 문제는 해커랭크의 MYSQL 문제였다. 프로그래머스와는 유형이 너무 다르고 더 어려웠다.. BTS 테이블에서 p 속성은 n의 부모를 의미한다. 즉, p 속성의 집합에 등장하지 않는 n들은 누군가의 부모가 될 수 없다는 말과 같으므로 자식 노드들이다. 이 부분을 서브쿼리로 처리해주어야 했다.

 p 집합에서 중복을 제거한 값들에 포함되지 않는 n들을 찾는데 이때 p가 null인 노드는 root이기 때문에 제외해주어야 한다.