LeetCode--608. 树节点

39 阅读2分钟

1 题目描述

表: Tree

+-------------+------+  
| Column Name | Type |  
+-------------+------+  
| id          | int  |  
| p_id        | int  |  
+-------------+------+  

id 是该表中具有唯一值的列
该表的每行包含树中节点的 id 及其父节点的 id 信息
给定的结构总是一个有效的树

树中的每个节点可以是以下三种类型之一:

  • "Leaf": 节点是叶子节点
  • "Root": 节点是树的根节点
  • "lnner": 节点既不是叶子节点也不是根节点
    编写一个解决方案来报告树中每个节点的类型
    任意顺序 返回结果表

2 测试用例

2.1 示例 1

image.png
输入:
Tree table:

+----+------+  
| 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  |  
+----+-------+  

解释:
节点 1 是根节点, 因为它的父节点为空, 并且它有子节点 2 和 3
节点 2 是一个内部节点, 因为它有父节点 1 和子节点 4 和 5
节点 3, 4 和 5 是叶子节点, 因为它们有父节点而没有子节点

2.2 示例 2

image.png
输入:
Tree table:

+----+------+  
| id | p_id |  
+----+------+  
| 1  | null |  
+----+------+  

输出:

+----+-------+  
| id | type  |  
+----+-------+  
| 1  | Root  |  
+----+-------+  

**解释:**如果树中只有一个节点, 则只需要输出其根属性

3 解题思路

使用 case when 通过不同的条件, 查找出符合条件的数据

  1. 查询 Root 节点的数据, 匹配条件是 p_id 为空
select id,  
       case  
           when p_id is null  
               then 'Root'  
           end as type  
from Tree  
  1. 查询 Inner 节点的数据, 匹配条件: 当前 id 在其他结点的 p_id 中出现, 且当前节点的 pid 不为空
select id,  
       case  
           when p_id is null  
               then 'Root'  
           when id in (select p_id from Tree)  
               then 'Inner'  
           end as type  
from Tree  
  1. 剩下的就是 Leaf 结点

  2. 最终的 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  

查询结果

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