Tree Node

medium database sql

Problem

Tree(id, p_id). Label every node as 'Root' (p_id IS NULL), 'Leaf' (id not referenced as parent), or 'Inner'.

Inputt=[(1,null),(2,1),(3,1),(4,2),(5,2)]
Output[(1,'Root'),(2,'Inner'),(3,'Leaf'),(4,'Leaf'),(5,'Leaf')]
1 has no parent → Root; 2 has children → Inner; the rest have no children → Leaf.

SELECT id,
  CASE WHEN p_id IS NULL THEN 'Root'
       WHEN id IN (SELECT DISTINCT p_id FROM Tree WHERE p_id IS NOT NULL) THEN 'Inner'
       ELSE 'Leaf' END AS Type
FROM Tree;
Time: O(n) Space: O(n)