BiruLyu
8/23/2017 - 12:46 AM

608. Tree Node.sql

# Write your MySQL query statement below
SELECT DISTINCT t1.id, (
    CASE
    WHEN t1.p_id IS NULL  THEN 'Root'
    WHEN t1.p_id IS NOT NULL AND t2.id IS NOT NULL THEN 'Inner'
    WHEN t1.p_id IS NOT NULL AND t2.id IS NULL THEN 'Leaf'
    END
) AS Type 
FROM tree t1
LEFT JOIN tree t2
ON t1.id = t2.p_id


# 
select id,
       (case
         when p_id is NULL then 'Root'
         when id not in (select a.p_id from tree a) then 'Leaf'
         else 'Inner'
        end) as Type
from tree
order by id