--- tags: sql, LeetCode --- # 608. Tree Node `Tree Node` 透過`leetcode 608`[Tree Node](https://leetcode.com/problems/tree-node/)來練習 #### 使用table ![](https://i.imgur.com/8JZbgB4.png) id 是該表的主鍵列。 該表的每一行都包含有關節點的 id 及其在樹中的父節點的 id 的信息。 給定的結構總是一棵有效的樹。 ## 題目說明: 樹中的每個節點都可以是以下三種類型之一: "Leaf":如果節點是葉子(最下面的點)節點。 "Root":如果節點是樹的根(最上面的點)。 "Inner":如果該節點既不是葉節點也不是根節點(中間 不是最上面也不是最下面)。 編寫一個 SQL 查詢來報告樹中每個節點的類型。 返回按id升序排列的結果表。 查詢結果格式如下例所示。 ![](https://i.imgur.com/ZXpAlqG.png) ## 解題: 以下圖解為第一個例題 **1.** ```sql= SELECT P_ID FROM Table_1 ``` ![](https://i.imgur.com/DFMTYar.png) **2.** ```sql= SELECT * FROM Table_1 WHERE ID IN (SELECT P_ID FROM Table_1) ``` ![](https://i.imgur.com/NbY9tlB.png) **3.** ```sql= 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.** ```sql= select * from Table_1 M left outer join Table_1 A on M.id = A.p_id ``` ![](https://i.imgur.com/1RzX5vC.png) **2.** ```sql= 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 ```