跳到主要内容

608.树节点

序号题目难度
608题目链接中等

题目大意​

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

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

以 任意顺序 返回结果表。

表:Tree

Column NameType
idint
p_idint

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

示例 1​

⓵ /
⓶ ⓷ /
⓸ ⓹

输入​

Tree table:

idp_id
1null
21
31
42
52

输出​

idtype
1Root
2Inner
3Leaf
4Leaf
5Leaf

解释​

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

示例 2​

⓵

输入​

Tree table:

idp_id
1null

输出​

idtype
1Root

解释​

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

注意​

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

参考答案​

with t1 as (
select
id
,case when p_id is not null then 1 else 0 end has_parent
from Tree
),
t2 as (
select
p_id id
,max(case when id is not null then 1 else 0 end) has_child
from Tree
where p_id is not null
group by 1
)
select
t1.id
, case when t0.p_id is null then 'Root'
when coalesce(t2.has_child, 0) = 1 and t1.has_parent = 1 then 'Inner'
when coalesce(t2.has_child, 0) = 0 and t1.has_parent = 1 then 'Leaf'
end as type
from Tree t0
left join t1
on t0.id = t1.id
left join t2
on t1.id = t2.id
;