22. Node Classification
Hierarchical structures like file systems, organizational charts, or comment threads in a forum often need to differentiate between root, inner, and leaf nodes. Proper classification helps in rendering or processing the hierarchy efficiently.
You are given a table Tree:
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā p_id ā int ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
- id: The unique ID of a node (Primary Key).
- p_id: The ID of the parent node for this node.
- A node where p_id IS NULL represents the root of the tree (since it has no parent).
- The table forms a valid tree (i.e., it is connected and acyclic with one root).
Each node can be classified as:
āāāāāāāāā¦āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā Type ā Description ā ā āāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā⣠ā Root ā If p_id IS NULL (i.e., no parent) ā āāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā Leaf ā If the node does not appear as a parent of any other node ā āāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā Inner ā If the node has a parent (p_id is not NULL) and is also a ā ā ā parent to at least one other node ā āāāāāāāāā©āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Write a query to determine the type of each node in a tree structure. Each node should be labeled as one of the following:
- 'Root': if it has no parent
- 'Leaf': if it has no children
- 'Inner': if it has both a parent and children
The output can be in any order.
Example 1:
Example 1:
Input:
āāāāāā¦āāāāāāā ā id ā p_id ā ā āāāāā¬āāāāāā⣠ā 10 ā null ā āāāāāā©āāāāāāā
Expected Output:
āāāāāā¦āāāāāāā ā id ā type ā ā āāāāā¬āāāāāā⣠ā 10 ā Root ā āāāāāā©āāāāāāā
Explanation:
Node 10: p_id is null = Root
Example 2:
Example 2:
Input:
āāāāāā¦āāāāāāā ā id ā p_id ā ā āāāāā¬āāāāāā⣠ā 1 ā null ā āāāāāā¼āāāāāāā ā 2 ā 1 ā āāāāāā¼āāāāāāā ā 3 ā 1 ā āāāāāā¼āāāāāāā ā 4 ā 2 ā āāāāāā¼āāāāāāā ā 5 ā 2 ā āāāāāā©āāāāāāā
Expected Output:
āāāāāā¦āāāāāāāā ā id ā type ā ā āāāāā¬āāāāāāā⣠ā 1 ā Root ā āāāāāā¼āāāāāāāā ā 2 ā Inner ā āāāāāā¼āāāāāāāā ā 3 ā Leaf ā āāāāāā¼āāāāāāāā ā 4 ā Leaf ā āāāāāā¼āāāāāāāā ā 5 ā Leaf ā āāāāāā©āāāāāāāā
Explanation:
- Node 1: p_id is null ā Root
- Node 2: Has a parent (1) and children (4,5) ā Inner
- Node 3: Has a parent (1) but no children ā Leaf
- Node 4 & 5: Have parents (2) but no children ā Leaf
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.