608. Tree Node

Tree Node

透過leetcode 608Tree Node來練習

使用table

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

id 是該表的主鍵列。
該表的每一行都包含有關節點的 id 及其在樹中的父節點的 id 的信息。
給定的結構總是一棵有效的樹。

題目說明:

樹中的每個節點都可以是以下三種類型之一:

"Leaf":如果節點是葉子(最下面的點)節點。
"Root":如果節點是樹的根(最上面的點)。
"Inner":如果該節點既不是葉節點也不是根節點(中間 不是最上面也不是最下面)。
編寫一個 SQL 查詢來報告樹中每個節點的類型。

返回按id升序排列的結果表。

查詢結果格式如下例所示。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

解題:

以下圖解為第一個例題

1.

SELECT P_ID FROM Table_1

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

2.

SELECT * FROM Table_1 WHERE ID IN (SELECT P_ID FROM Table_1)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

3.

select id, case when p_id is null then 'Root' when id in (select p_id from tree) then 'Inner' else 'Leaf' end as Type FROM tree

以下圖解為第二個例題

1.

select * from Table_1 M left outer join Table_1 A on M.id = A.p_id

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

2.

select distinct M.id, case when M.p_id is null then 'Root' when A.p_id is not null then 'Inner' else 'Leaf' end as 'type' from Tree M left outer join Tree A on M.id = A.p_id