Binary Tree Nodes - Problem
Given a table representing a binary tree structure, your task is to classify each node based on its position in the tree hierarchy.
The Tree table contains:
N: The node value (unique identifier)P: The parent node value (NULL for root)
You need to determine the node type for each node:
- Root: The top-level node with no parent (P is NULL)
- Leaf: A node that has no children
- Inner: A node that has both a parent and at least one child
Return the results ordered by node value in ascending order.
Example:
Input: +---+------+ | N | P | +---+------+ | 1 | 2 | | 2 | 5 | | 3 | 2 | | 5 | NULL | +---+------+ Output: +---+-------+ | N | Type | +---+-------+ | 1 | Leaf | | 2 | Inner | | 3 | Leaf | | 5 | Root | +---+-------+
Input & Output
example_1.sql โ Basic Tree
$
Input:
Tree table:
+---+------+
| N | P |
+---+------+
| 1 | 2 |
| 2 | 5 |
| 3 | 2 |
| 5 | NULL |
+---+------+
โบ
Output:
+---+-------+
| N | Type |
+---+-------+
| 1 | Leaf |
| 2 | Inner |
| 3 | Leaf |
| 5 | Root |
+---+-------+
๐ก Note:
Node 5 is Root (P=NULL), Node 2 is Inner (has children 1,3), Nodes 1,3 are Leaf (no children)
example_2.sql โ Single Node
$
Input:
Tree table:
+---+------+
| N | P |
+---+------+
| 1 | NULL |
+---+------+
โบ
Output:
+---+------+
| N | Type |
+---+------+
| 1 | Root |
+---+------+
๐ก Note:
Single node tree where node 1 is the root with no parent and no children
example_3.sql โ Linear Tree
$
Input:
Tree table:
+---+------+
| N | P |
+---+------+
| 1 | 2 |
| 2 | 3 |
| 3 | NULL |
+---+------+
โบ
Output:
+---+-------+
| N | Type |
+---+-------+
| 1 | Leaf |
| 2 | Inner |
| 3 | Root |
+---+-------+
๐ก Note:
Linear tree: 3 (Root) -> 2 (Inner) -> 1 (Leaf). Node 3 has no parent, node 1 has no children, node 2 has both.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Root Node
Find the node where P IS NULL - this is the tree root
2
Find Parent-Child Relationships
JOIN the table with itself to match parents with their children
3
Count Children
Use COUNT to determine how many children each node has
4
Classify Node Types
Apply logic: Root (no parent), Leaf (no children), Inner (has both)
Key Takeaway
๐ฏ Key Insight: Use LEFT JOIN with GROUP BY to efficiently determine parent-child relationships and classify all nodes in a single query pass
Time & Space Complexity
Time Complexity
O(n log n)
Single pass with JOIN operation, optimized by database engine
โก Linearithmic
Space Complexity
O(n)
Temporary space for JOIN operation and grouping
โก Linearithmic Space
Constraints
- 1 โค Number of nodes โค 103
- 1 โค N โค 100
- Each N is unique in the table
- Exactly one node will have P = NULL (the root)
- All P values (except NULL) must exist as N values in the table
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code