Tree Node
EasyPremium
Given a binary tree, identify which nodes are leaf nodes, root nodes or inner nodes.
- Leaf nodes: A node with no children
- Root nodes: A node with no parent
- Inner nodes: A node with both children and parent nodes
You are given the following table tree_node_table:
where p_id is the id of the parent node. Your output should contain the following columns: id, node_types (’Root’, ‘Inner’, ‘Leaf’).
SELECT id,
(CASE
WHEN p_id IS NULL
THEN 'Root'
WHEN p_id IN (SELECT id FROM tree_node_table) AND id IN (SELECT p_id FROM tree_node_table)
THEN 'Inner'
ELSE 'Leaf'
END) node_types
FROM tree_node_table
ORDER BY id;
-- Write your query here select id, (case when p_id is null then 'Root' when p_id in (select id from tree_node_table) and id in (select p_id from tree_node_table) then 'Inner' else 'Leaf' end) as node_types from tree_node_table order by 1;