Tree Node: Root/Leaf/Inner

4pts
Algorithm

Problem Statement

Given a table Tree containing node ids and their parent ids (p_id), write a query to label each node as one of the following:

  • Root: If the node is the root of the tree (p_id is NULL).
  • Leaf: If the node is a leaf node (not a parent of any other node).
  • Inner: If the node is neither a root nor a leaf.

Rules:

  • Every node has a unique id.
  • Output columns: id, type.
  • Results must be sorted by id in ascending order.
Tests your understanding of
Tree, Conditional Logic and Subqueries

Input Tables

Tree
id(INTEGER)p_id(INTEGER)
1null
21
31
42
52
Node_Metadata
id(INTEGER)node_value(VARCHAR)
1Start
Tree_Audit
audit_id(INTEGER)id(INTEGER)change_date(DATE)
50112026-02-09

Expected Output

id(INTEGER)type(VARCHAR)
1Root
2Inner
3Leaf
4Leaf
5Leaf

Tags

MediumTreeConditional LogicSubqueries
15-20 min
62%

Hints