-
해커랭크 Binary Tree Nodes (CASE, 서브쿼리)Programing Language/SQL 2025. 6. 16. 09:59반응형
https://www.hackerrank.com/challenges/binary-search-tree-1/problem
Binary Tree Nodes | HackerRank
Write a query to find the node type of BST ordered by the value of the node.
www.hackerrank.com
문제 정의 (영어 -> 한국어 번역 후 문제 파악하기)
두 개의 열 N 과 P를 포함하는 BST 테이블이 주어졌습니다 . 여기서 N은 이진 트리 의 노드 값을 나타내고 P 는 N 의 부모입니다 .
노드 값을 기준으로 정렬된 이진 트리 의 노드 유형을 찾는 쿼리를 작성하세요. 각 노드에 대해 다음 중 하나를 출력하세요.
- Root: If node is root node.
- Leaf: If node is leaf node.
- Inner: If node is neither root nor leaf node.


문제 접근
- N별로 각자 root, leaf, inner 구분하기
- 접근
- case 구문 처리
- root : p가 없는 경우 ex) 5
- inner : p에 n이 있는 경우
- leaf : root, leaf 아닌 경우
- exists 활용 : 단순하게 n=p 확인
- left join 활용 : 유니크한 p가 n에 있는 확인
- case 구문 처리
/* -- N별로 각자 root, leaf, inner 구분하기 -- 접근 -- case 구문 처리 -- root : p가 없는 경우 ex) 5 -- inner : n 이 p인 경우 -- leaf : root, leaf 아닌 경우 */ -- ver1. exists 활용 select n , case when p is null then 'Root' when exists (select 1 from bst b2 where b2.p = b1.n) then 'Inner' else 'Leaf' end ny from bst b1 order by n ; -- ver2. left join 활용 select b1.n , case when b1.p is null then 'Root' when b2.p is not null then 'Inner' else 'Leaf' end ny from bst b1 left join ( select distinct p from bst ) b2 on b1.n = b2.p order by b1.n반응형'Programing Language > SQL' 카테고리의 다른 글
해커랭크 Symmetric Pairs (셀프 JOIN, 조건) (0) 2025.06.16 해커랭크 Ollivander's Inventory (복합 조건 JOIN) (0) 2025.06.16 해커랭크 Weather Observation Station 20 (중앙값, 윈도우 함수) (0) 2025.06.16 해커랭크 Placements (JOIN, 서브쿼리) (1) 2025.06.15 해커랭크 Top Competitors (다중 JOIN, 필터링) (0) 2025.06.15