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.
대강 해설
2개의 컬럼으로 이루어진 BST 테이블을 드립니다. N과 P로 구성되어 있으며 N은 이진트리의 노드, P는 N의 부모를 가르킵니다.
해당 노드가 Root인지, Leaf인지, Inner인지 구분하여 출력 해주세요.
필요한 기능
- join
- a join b on a.p = b.n -> a와 b를 a.p와 b.n을 매칭시켜 join을 진행합니다.
코드
더보기
SELECT BST.N,
(CASE
WHEN BST.P IS NULL THEN 'Root'
WHEN B.PC IS NULL THEN 'Leaf'
ELSE 'Inner'
END)
FROM BST
LEFT JOIN (
SELECT P, COUNT(P) AS PC
FROM BST
GROUP BY P
) AS B ON BST.N = B.P
ORDER BY BST.N ASC;
728x90
'서버 > MYSQL' 카테고리의 다른 글
| [MYSQL] Hackerrank - Occupations (0) | 2022.12.31 |
|---|---|
| [MYSQL] Hackerrank - The PADS (0) | 2022.12.22 |
| [MYSQL] Hackerrank - Type of Triangle (0) | 2022.12.21 |
| [MYSQL] Hackerrank - Employee Salaries (0) | 2022.12.16 |
| [MYSQL] Hackerrank - Employee Names (0) | 2022.12.16 |
댓글