반응형
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
해결 방법 : SELECT CASE
- 한 가지, 주의할 점은 not in 연산을 할 때, 서브 쿼리 결과값 집합에 null이 포함되어 있으면 결과 자체가 null이 된다. (in 연산은 괜찮다.) 궁금해서 찾아보니 이유는 다음과 같다.
- X in (A, B, C, null) means, (X = A) or (X = B) or = (X = C) or (X = null) 따라서 X가 A, B, C 중에 하나이면 X가 선택된다. (X = null은 false, null 비교는 'is null'을 사용해야하므로,)
- X not in (A, B, C, null) means, (X != A) and (X != B) and (X != C) and (X != null) 인데, X != null은 무조건 false를 반환하기 때문에 and 연산으로 인해 X가 어떤것도 포함하지 못한다.
SELECT n,
case when p is null then 'Root'
when n not in (SELECT p FROM bst WHERE p is not null) then 'Leaf'
when n in (SELECT p FROM bst) then 'Inner' end as pos
FROM bst
ORDER BY n;
출처
wjheo.tistory.com/entry/IN%EA%B3%BC-NOT-IN%EC%9D%98-%ED%95%A8%EC%A0%95
반응형
'IT study > SQL' 카테고리의 다른 글
Weather Observation Station 18 ~ 19 (0) | 2021.04.23 |
---|---|
New Companies (+ 형 변환) (0) | 2021.04.22 |
Occupations (SET, CASE) (0) | 2021.04.17 |
15 days of learning SQL (0) | 2021.04.15 |
Interviews (0) | 2021.04.15 |