Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[LeetCode] 608. Tree Node

์ธ” 2023. 5. 16. 14:11

๐Ÿ“ข ๋ณธ ํฌ์ŠคํŒ…์— ํ™œ์šฉ๋˜๋Š” ๊ธฐ๋ณธ ๋ฌธ์ œ ๋ฐ ์ž๋ฃŒ ์ถœ์ฒ˜๋Š”

       ๋ฆฌํŠธ์ฝ”๋“œ Problems, https://leetcode.com/problemset/all/์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค.


โœ” ๋ฌธ์ œ

https://leetcode.com/problems/tree-node/

 

Tree Node - LeetCode

Can you solve this real interview question? Tree Node - Table: Tree +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | p_id | int | +-------------+------+ id is the primary key column for this table. Each row of this table

leetcode.com

Table : 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 an SQL query to report the type of each node in the tree.

Return the result table in any order.

The query result format is in the following example.

 

Example 1:


โœ” ํ’€์ด

  ๋ฌธ์ œ ์š”๊ตฌ์‚ฌํ•ญ  

 

id์™€ p_id ๊ด€๊ณ„์— ๋”ฐ๋ผ id์˜ type์„ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

โ‘  p_id๊ฐ€ null์ด๋ฉด ํ•ด๋‹น id๋Š” Root

โ‘ก p_id๊ฐ€ ์กด์žฌํ•˜๊ณ  ํ•ด๋‹น id๊ฐ€ ๋ˆ„๊ตฐ๊ฐ€์˜ p_id๊ฐ€ ๋œ๋‹ค๋ฉด Inner

โ‘ข p_id๊ฐ€ ์กด์žฌํ•˜๊ณ  ํ•ด๋‹น id๊ฐ€ ๋ˆ„๊ตฐ๊ฐ€์˜ p_id๊ฐ€ ๋˜์ง€ ์•Š๋Š”๋‹ค๋ฉด Leaf

 

p_id์˜ ์กด์žฌ ์œ ๋ฌด์™€ ๊ด€๊ณ„๋ฅผ ์‰ฝ๊ฒŒ ๋น„๊ตํ•˜๊ธฐ ์œ„ํ•ด Tree ํ…Œ์ด๋ธ” ๊ธฐ์ค€์œผ๋กœ left joinํ•œ๋‹ค.

โ€ป ์ค‘์š”ํ•œ ๊ฒƒ์€ ๊ณตํ†ต ์ปฌ๋Ÿผ์„ ๊ธฐ์กด tree ํ…Œ์ด๋ธ”(T1)์˜ id์™€ ์กฐ์ธํ•˜๋Š” tree ํ…Œ์ด๋ธ”(T2)์˜ p_id๋ฅผ ์กฐ์ธ ์กฐ๊ฑด์œผ๋กœ ์žก๋Š” ๊ฒƒ.

์กฐ์ธํ•˜๋ฉด ์˜ˆ์‹œ ํ…Œ์ด๋ธ”์—์„œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜จ๋‹ค.

T1 T2
id p_id p_id id
1 null 1 3
1 null 1 2
2 1 2 5
2 1 2 4
3 1 null null
4 2 null null
5 2 null null

์กฐ์ธ ํ›„  โ‘ , โ‘ก, โ‘ข์„ CASE๋ฌธ์„ ํ™œ์šฉํ•ด์„œ ์กฐ๊ฑด์œผ๋กœ ์ˆœ์ฐจ ์ ์šฉํ•ด์ค€๋‹ค.

SELECT DISTINCT T1.id AS id, 
CASE WHEN T1.p_id is null THEN 'Root'
WHEN T2.id is not null THEN 'Inner'
ELSE 'Leaf'
END AS 'type' 
 FROM Tree T1
 LEFT JOIN Tree T2
 ON T1.id = T2.p_id