diff --git a/README.md b/README.md index 71f6325..a7630ab 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ Useful for preparing for technical interviews and improving your SQL skills. - [570. Managers with at Least 5 Direct Reports](./leetcode/medium/570.%20Managers%20with%20at%20Least%205%20Direct%20Reports.sql) - [585. Investments in 2016](./leetcode/medium/585.%20Investments%20in%202016.sql) - [602. Friend Requests II: Who Has the Most Friends](./leetcode/medium/602.%20Friend%20Requests%20II:%20Who%20Has%20the%20Most%20Friends.sql) + - [608. Tree Node](./leetcode/medium/608.%20Tree%20Node.sql) - [626. Exchange Seats](./leetcode/medium/626.%20Exchange%20Seats.sql) - [1045. Customers Who Bought All Products](./leetcode/medium/1045.%20Customers%20Who%20Bought%20All%20Products.sql) - [1070. Product Sales Analysis III](./leetcode/medium/1070.%20Product%20Sales%20Analysis%203.sql) diff --git a/leetcode/medium/608. Tree Node.sql b/leetcode/medium/608. Tree Node.sql new file mode 100644 index 0000000..0ddf426 --- /dev/null +++ b/leetcode/medium/608. Tree Node.sql @@ -0,0 +1,38 @@ +/* +Question 608. Tree Node +Link: https://leetcode.com/problems/tree-node/description/?envType=problem-list-v2&envId=database + +Table: Tree + ++-------------+------+ +| Column Name | Type | ++-------------+------+ +| id | int | +| p_id | int | ++-------------+------+ +id is the column with unique values for this table. +Each row of this table contains information about the id of a node and the id of its parent node in a tree. +The given structure is always a valid tree. + + +Each node in the tree can be one of three types: + +"Leaf": if the node is a leaf node. +"Root": if the node is the root of the tree. +"Inner": If the node is neither a leaf node nor a root node. +Write a solution to report the type of each node in the tree. + +Return the result table in any order. +*/ + +SELECT + t.id, + (CASE + WHEN t.p_id IS NULL THEN 'Root' + WHEN t.id IN ( + SELECT DISTINCT t1.p_id + FROM Tree AS t1 + ) THEN 'Inner' + ELSE 'Leaf' + END) AS type --noqa: RF04 +FROM Tree AS t