(해커랭크) Midium. Binary Tree Nodes

chaechae·2023년 2월 28일
0

코딩테스트(SQL) 

목록 보기
9/22
post-thumbnail

문제 )

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.
    (자세한 문제는 이곳을 참고해 주세요! Binary Tree Nodes)

요약하자면 뿌리node 는 'Root' 로 잎node 는 'leaf' 뿌리와 잎사이에 있는경우 'Inner'로 표시하라는 문제입니다. 아래의 예시 문제의 경우,


SELECT n
    , CASE WHEN P IS NULL THEN 'Root' 
        WHEN N IN(SELECT DISTINCT P FROM BST) THEN 'Inner' 
        ELSE 'Leaf' END AS A
FROM BST
ORDER BY N

풀이과정

  • 가장 먼저 Root에 해당하는 5의 경우 부모노드가 없으므로 P 가 NULL 인 경우로 처리했습니다.
  • 그다음 Inner에 해당하는 8,2 의 경우 N 에도 존재하고 P에도 존재 해야하므로 IN절을 이용하여 포함 여부를 확인습니다. 그 외 나머지는 Leaf에 해당합니다.
profile
게임 혹은 다양한 컨텐츠가 있는 곳을 좋아합니다. 시리즈를 참고하시면 편하게 글을 보실 수 있습니다🫠

0개의 댓글