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:
Sample Input
Sample Output
1 Leaf
2 Inner
3 Leaf
5 Root
6 Leaf
8 Inner
9 Leaf
Explanation
SELECT
B1.N,
(CASE
WHEN B1.P IS NULL THEN "Root"
WHEN B3.P IS NOT NULL THEN "Leaf"
ELSE "Inner"
END) AS result
FROM BST AS B1 LEFT OUTER JOIN BST AS B2 ON B1.P = B2.N
LEFT OUTER JOIN BST AS B3 ON B2.P = B3.N
ORDER BY B1.N ASC;
SELF JOIN
λ°©λ²μ μ΄μ©νλ€. νμ§λ§ MySQLμμλ ν΄λΉ ν¨μλ₯Ό μ§μνμ§ μμΌλ―λ‘ LEFT OUTER JOIN
ν¨μλ₯Ό μ€μ²©νμ¬ νμλ€.
μμλ₯Ό λ€μλ©΄ λΆν μ§μλ€μ λ΄λΉνλ μμ¬κ° μλ€κ³ μκ°νλ©΄ λλ€.
λΆν | μμ¬ | λΆν | μμ¬ |
---|---|---|---|
1 | 2 | 2 | 4 |
λΆν 1μ μμ¬λ 2μ΄κ³ , 2μ μμ¬λ 4μ΄λ€.
λ§μ½ 4κ° μ§μ₯ λ΄μ μ μΌ λμ μ§μλ₯Ό κ°μ‘λ€κ³ κ°μ νλ©΄, 4μ μμ¬λ μ‘΄μ¬νμ§ μκΈ° λλ¬Έμ NULL
μ΄ μ
λ ₯λλ€.
λ°λΌμ μμ μ리λ₯Ό μ΄μ©νμ¬ νμλ€.