cswork / libraryOpen practice workspace

Coding questions · Oracle

Classify Tree Nodes in SQL

Classify each tree node as Root, Inner, or Leaf in PostgreSQL using its parent ID and whether it has children, returning one classification per node.

Write a PostgreSQL query that classifies every node in a tree as Root, Inner, or Leaf.

Table

Tree contains one row per node:

ColumnTypeMeaning
idintegerUnique, non-null node identifier
pidinteger, nullableParent node identifier, or NULL when the node has no parent

The input represents a nonempty tree. Each non-null pid refers to the id of its parent node.

Classification rules

  • Root: the node has no parent, so its pid is NULL.
  • Inner: the node has a parent and at least one child. A child is a row whose pid equals this node's id.
  • Leaf: the node has a parent and no children.

A root is classified as Root regardless of whether it has children, including when it is the tree's only node.

Required output

Return exactly one row per input node, with columns id and type. The type value must be exactly Root, Inner, or Leaf according to the rules above. Result rows may appear in any order.

Example

Input Tree:

idpid
1NULL
21
31
42

Expected result, shown in identifier order only for readability:

idtype
1Root
2Inner
3Leaf
4Leaf

Classify Tree Nodes in SQL

Table tree

columntypeconstraints
idINTEGERPRIMARY KEY
pidINTEGER

Sample data:

idpid
37
42NULL
110
1690
-1242
9916
742
7522
-80
907
042
516
422
617
22-12
-390

Expected output

idtype
-12Inner
-8Leaf
-3Leaf
0Inner
3Leaf
4Leaf
5Leaf
7Inner
11Leaf
16Inner
22Inner
42Root
61Leaf
75Leaf
90Inner
99Leaf

Hints

  1. Return one classification row for every input node.
  2. A root remains Root whether or not it has children.