Tree Node - Problem
Imagine you're building a family tree analyzer! You have a database table containing information about nodes in a tree structure, where each node has an id and a p_id (parent ID).
Your mission: Classify each node as one of three types:
- "Root" - The ancestor of all nodes (has no parent, p_id is null)
- "Leaf" - A node with no children (appears as p_id for no other nodes)
- "Inner" - A node that has both a parent and at least one child
The tree structure is guaranteed to be valid, meaning there are no cycles and exactly one root node.
Table Structure:
Tree +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | p_id | int | +-------------+------+
Return the result showing each node's id and its corresponding type, in any order.
Input & Output
example_1.sql โ Basic Tree
$
Input:
Tree table:
+----+------+
| id | p_id |
+----+------+
| 1 | NULL |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
+----+------+
โบ
Output:
+----+-------+
| id | type |
+----+-------+
| 1 | Root |
| 2 | Inner |
| 3 | Leaf |
| 4 | Leaf |
+----+-------+
๐ก Note:
Node 1 is the root (p_id is NULL). Node 2 has both parent (1) and child (4), so it's Inner. Nodes 3 and 4 have parents but no children, so they're Leaf nodes.
example_2.sql โ Single Node Tree
$
Input:
Tree table:
+----+------+
| id | p_id |
+----+------+
| 1 | NULL |
+----+------+
โบ
Output:
+----+------+
| id | type |
+----+------+
| 1 | Root |
+----+------+
๐ก Note:
A single node tree has only one node, which is the root by definition (p_id is NULL).
example_3.sql โ Linear Tree
$
Input:
Tree table:
+----+------+
| id | p_id |
+----+------+
| 1 | NULL |
| 2 | 1 |
| 3 | 2 |
| 4 | 3 |
+----+------+
โบ
Output:
+----+-------+
| id | type |
+----+-------+
| 1 | Root |
| 2 | Inner |
| 3 | Inner |
| 4 | Leaf |
+----+-------+
๐ก Note:
This is a linear tree (like a linked list). Node 1 is Root, nodes 2 and 3 are Inner (have both parent and child), and node 4 is Leaf (has parent but no children).
Constraints
- 1 โค Number of nodes โค 104
- 1 โค Node ID โค 109
- Parent ID (p_id) can be NULL for root node only
- The tree structure is guaranteed to be valid (no cycles, single root)
- Each node ID appears exactly once in the table
Visualization
Tap to expand
Understanding the Visualization
1
Identify Root
Find the node with p_id = NULL - this is the tree root
2
Map Relationships
Create parent-child mappings to understand tree structure
3
Count Children
For each node, count how many children it has
4
Classify Nodes
Apply rules: Root (no parent), Inner (has children), Leaf (no children)
Key Takeaway
๐ฏ Key Insight: Use SQL JOINs and aggregation to efficiently determine parent-child relationships and classify nodes based on whether they have parents and children.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code