#608
Tree Node
MediumDatabaseHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
By using a single pass to create a set of child nodes, we can efficiently classify each node in one go.
⚙️
Algorithm
3 steps- 1Step 1: Create a set of all child node ids by selecting distinct p_id values from the Tree table.
- 2Step 2: For each node, check if it is in the child set to determine if it is a leaf or inner node.
- 3Step 3: Classify the node as 'Root', 'Inner', or 'Leaf' based on its p_id and presence in the child set.
solution.py10 lines
1WITH ChildNodes AS (
2 SELECT DISTINCT p_id FROM Tree WHERE p_id IS NOT NULL
3)
4SELECT id,
5 CASE
6 WHEN p_id IS NULL THEN 'Root'
7 WHEN id IN (SELECT * FROM ChildNodes) THEN 'Inner'
8 ELSE 'Leaf'
9 END AS type
10FROM Tree;ℹ
Complexity note: The time complexity is O(n) because we only need to scan through the nodes a couple of times: once to create the child set and once to classify each node.
- 1Understanding the structure of trees is crucial for identifying node types.
- 2Using sets can significantly improve lookup times when classifying nodes.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.