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 Process1 (Root)2 (Inner)3 (Leaf)4 (Leaf)5 (Leaf)Classification Rules:● Root: p_id IS NULL● Inner: has parent AND children● Leaf: has parent but NO childrenSQL Strategy:1. LEFT JOIN Tree with itself2. GROUP BY to find children3. CASE WHEN for classification
Understanding the Visualization
1
Input Tree
Table with id and parent_id relationships
2
Self-Join
LEFT JOIN to find parent-child connections
3
Classify
CASE WHEN to determine Root/Inner/Leaf types
Key Takeaway
🎯 Key Insight: Use self-joins to identify parent-child relationships, then classify nodes based on the presence of parents and children
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