forked from nathan-abela/HackerRank-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04 - Binary Tree Nodes.sql
More file actions
33 lines (27 loc) · 964 Bytes
/
04 - Binary Tree Nodes.sql
File metadata and controls
33 lines (27 loc) · 964 Bytes
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
31
32
33
-- ========================
-- Information
-- ========================
-- Direct Link: https://www.hackerrank.com/challenges/binary-search-tree-1/problem
-- Difficulty: Medium
-- Max Score: 30
-- DBMS: mySQL
-- ========================
-- Solution
-- ========================
SELECT
CASE
WHEN P IS NULL
THEN CONCAT(N, ' Root')
WHEN N IN (SELECT DISTINCT P FROM BST)
THEN CONCAT(N, ' Inner')
ELSE CONCAT(N, ' Leaf')
END
FROM BST
ORDER BY N ASC;
-- ========================
-- Explanation
-- ========================
-- 'CASE' goes through conditions and return a value when the first condition is met (like an IF-ELSE statement). So, once a condition is true, it will stop reading and return the result.
-- If no conditions are true, it will return the value in the ELSE clause.
-- If there is no ELSE part and no conditions are true, it returns NULL.
-- CONCAT() function adds two or more expressions together