일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- coding test
- 코딩테스트
- counter
- AARRR
- lv4
- Stack
- itertools
- programmers
- mysql
- Queue
- 프로그래머스
- 코딩
- hackerrank
- join
- cte
- Level2
- 조합
- tableau
- level4
- import re
- 파이썬
- collections
- sql
- time complexity
- Growth hacking
- python
- 코테
- lambda
- 완전탐색
- coding
Archives
- Today
- Total
ror_coding
[HackerRank] Binary Tree Nodes 본문
728x90
WITH RECURSIVE (CTE) 로 Level 구하기 !!! 매우 중요!
Question
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.
Sample Input
Sample Output
1 Leaf
2 Inner
3 Leaf
5 Root
6 Leaf
8 Inner
9 Leaf
Explanation
The Binary Tree below illustrates the sample:
Point
- RECURSIVE 구문을 통해 Level을 입력한 후 마지막 node (leaf) 의 레벨이 적힌 열(MAX_LV)을 생성한다.
- 1레벨을 'Root', 마지막 레벨을 'Leaf'로 입력하고 나머진 Inner로 넣어준다.
Code
WITH RECURSIVE GENERATION AS(
SELECT N, P, 1 AS LV
FROM BST
WHERE P IS NULL
UNION ALL
SELECT C.N, C.P, LV + 1
FROM BST C
JOIN GENERATION G
ON C.P = G.N
),
GEN_WITH_MAX AS(
SELECT *, MAX(LV) OVER() AS MAX_LV
FROM GENERATION
)
SELECT N,
CASE
WHEN LV = 1 THEN 'Root'
WHEN LV = MAX_LV THEN 'Leaf'
ELSE 'Inner'
END AS 'NODE'
FROM GEN_WITH_MAX
ORDER BY 1
now me

On my github
728x90
'Coding Test > SQL' 카테고리의 다른 글
[HackerRank] Type of Triangle (0) | 2025.06.14 |
---|---|
[HackerRank] Symmetric Pairs (0) | 2025.06.14 |
[HackerRank] Occupations (0) | 2025.04.05 |
[Programmers Lv.5] 멸종위기의 대장균 찾기 - 301651 (0) | 2025.01.16 |
[Programmers Lv.5] 상품을 구매한 회원 비율 구하기 - 131534 (0) | 2025.01.16 |