Sqlserver中的 树节点

题目: https://leetcode.cn/problems/tree-node/

给定一个表 tree,id 是树节点的编号, p_id 是它父节点的 id 。

+----+------+
| id | p_id |
+----+------+
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
+----+------+
树中每个节点属于以下三种类型之一:

叶子:如果这个节点没有任何孩子节点。
根:如果这个节点是整棵树的根,即没有父节点。
内部节点:如果这个节点既不是叶子节点也不是根节点。
 

写一个查询语句,输出所有节点的编号和节点的类型,并将结果按照节点编号排序。上面样例的结果为:

 

+----+------+
| id | Type |
+----+------+
| 1 | Root |
| 2 | Inner|
| 3 | Leaf |
| 4 | Leaf |
| 5 | Leaf |
+----+------+

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/tree-node
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

官方有三种解法,第三种与第二种类似,主要是unoin,与case when

记录下我的写法:
select a.id,case  when a.p_id is  null then 'Root' 
when a.id not in ( select p_id from tree where p_id is not null ) then 'Leaf' //注意点,如果这里不写 p_id is not null ,查不出来数据
when  a.id in( select p_id from tree where p_id is not null )   then  'Inner'
end as Type
from tree  as a
 
 
posted @ 2022-12-03 21:00  yinghualeihenmei  阅读(40)  评论(0编辑  收藏  举报