Tree Node - Problem

Given a table Tree representing a tree structure, classify each node as one of three types:

  • "Leaf": A node with no children
  • "Root": The top node with no parent (p_id is null)
  • "Inner": A node that has both parent and children

Write a SQL query to return the id and type of each node in the tree.

Table Schema

Tree
Column Name Type Description
id PK int Unique identifier for each node
p_id int Parent node ID, NULL for root node
Primary Key: id
Note: Each row represents a node in the tree with its parent relationship

Input & Output

Example 1 — Complete Tree Structure
Input Table:
id p_id
1
2 1
3 1
4 2
5 2
Output:
id type
1 Root
2 Inner
3 Leaf
4 Leaf
5 Leaf
💡 Note:

Node 1 has no parent (p_id is NULL) so it's the Root. Node 2 has parent 1 and children 4,5 so it's Inner. Nodes 3,4,5 have parents but no children so they're Leaf nodes.

Example 2 — Single Root Node
Input Table:
id p_id
1
Output:
id type
1 Root
💡 Note:

When there's only one node with no parent, it's classified as the Root node.

Constraints

  • 1 ≤ Node count ≤ 1000
  • 1 ≤ id ≤ 1000
  • Tree structure is always valid
  • Each id is unique

Visualization

Tap to expand
Tree Node Classification INPUT Tree Structure 1 2 3 4 5 Tree Table id p_id 1 NULL 2 1 3 1 ALGORITHM STEPS 1 Check Root p_id IS NULL 2 Check Leaf id NOT IN p_id list 3 Check Inner Has parent AND children 4 Use CASE Classify each node SELECT id, CASE WHEN p_id IS NULL THEN 'Root' WHEN id NOT IN (p_id) THEN 'Leaf' ELSE 'Inner' END AS type FINAL RESULT Classified Tree 1 Root 2 Inner 3 Leaf 4 5 Leaf Output id type 1 Root 2 Inner 3 Leaf Key Insight: Use CASE WHEN with subqueries to classify nodes. Root has NULL parent, Leaf has no children (id not in parent list), Inner has both. Self-join or subquery checks if id appears as p_id. TutorialsPoint - Tree Node | Optimal Solution
Asked in
Facebook 28 Amazon 22 Microsoft 18
34.5K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen