力扣之608.树节点

1. 608.树节点

1.1 题干

表:Tree

±------------±-----+
| Column Name | Type |
±------------±-----+
| id | int |
| p_id | int |
±------------±-----+
id 是该表中具有唯一值的列。
该表的每行包含树中节点的 id 及其父节点的 id 信息。
给定的结构总是一个有效的树。

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

“Leaf”:节点是叶子节点。
“Root”:节点是树的根节点。
“lnner”:节点既不是叶子节点也不是根节点。
编写一个解决方案来报告树中每个节点的类型。

以 任意顺序 返回结果表。

结果格式如下所示。

示例 1:
在这里插入图片描述

输入:
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:
在这里插入图片描述
输入:
Tree table:
±—±-----+
| id | p_id |
±—±-----+
| 1 | null |
±—±-----+
输出:
±—±------+
| id | type |
±—±------+
| 1 | Root |
±—±------+
解释:如果树中只有一个节点,则只需要输出其根属性。

注意:本题与 3054. 二叉树节点 一致。

1.2 准备数据

Create table If Not Exists Tree (id int, p_id int)
Truncate table Tree
insert into Tree (id, p_id) values ('1', NULL)
insert into Tree (id, p_id) values ('2', '1')
insert into Tree (id, p_id) values ('3', '1')
insert into Tree (id, p_id) values ('4', '2')
insert into Tree (id, p_id) values ('5', '2')

1.3 解决方法

select id,(case
       when p_id is null then 'Root'
       when id in (select p_id from Tree) then 'Inner'
       when id not in (select p_id from Tree where p_id is not null) then 'Leaf'
       end) as type
       from Tree;

注意in后面可以有nullnot in后面不能有null

1.4 结果截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值