일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 코딩테스트
- time complexity
- lambda
- 코테
- Stack
- cte
- Level2
- 연습문제
- 프로그래머스
- Queue
- 코딩
- lv4
- 완전탐색
- python
- programmers
- 조합
- import re
- 시간복잡도
- itertools
- coding test
- BFS
- mysql
- join
- coding
- 파이썬
- counter
- sql
- collections
- 데이터분석
- level4
- 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
'Algorithm > SQL' 카테고리의 다른 글
[HackerRank] Occupations (0) | 2025.04.05 |
---|---|
[Programmers Lv.5] 멸종위기의 대장균 찾기 - 301651 (0) | 2025.01.16 |
[Programmers Lv.5] 상품을 구매한 회원 비율 구하기 - 131534 (0) | 2025.01.16 |
[Programmers Lv.4] 언어별 개발자 분류하기 - 276036 (0) | 2025.01.12 |
[Programmers Lv.4] 특정 기간동안 대여 가능한 자동차들의 대여비용 구하기 - 157339 (0) | 2025.01.12 |