当前位置:网站首页>LeetCode-608. 树节点
LeetCode-608. 树节点
2022-04-23 09:55:00 【边界流浪者】
给定一个表 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 |
+----+------+
解释
节点 '1' 是根节点,因为它的父节点是 NULL ,同时它有孩子节点 '2' 和 '3' 。
节点 '2' 是内部节点,因为它有父节点 '1' ,也有孩子节点 '4' 和 '5' 。
节点 '3', '4' 和 '5' 都是叶子节点,因为它们都有父节点同时没有孩子节点。
样例中树的形态如下:
1
/ \
2 3
/ \
4 5
注意
如果树中只有一个节点,你只需要输出它的根属性。
# Write your MySQL query statement below
SELECT t1.id, 'Leaf' AS Type FROM tree AS t1
WHERE t1.id
NOT IN
(
SELECT DISTINCT p_id
FROM tree
WHERE p_id IS NOT NULL
) AND t1.p_id IS NOT NULL
UNION
SELECT DISTINCT i1.id, 'Inner' AS Type
FROM tree AS i1 INNER JOIN tree AS i2
ON i1.id = i2.p_id
WHERE i1.id = i2.p_id AND i1.p_id IS NOT NULL AND i2.id IS NOT NULL
UNION
SELECT id, 'Root' AS Type
FROM tree WHERE p_id IS NULL;
版权声明
本文为[边界流浪者]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_16542775/article/details/124306091
边栏推荐
- 自定义登录失败处理
- 杰理之更准确地确定异常地址【篇】
- 构建元宇宙时代敏捷制造的九种能力
- 第一章 Oracle Database In-Memory 相关概念(IM-1.1)
- Planning and construction of industrial meta universe platform
- Integral function and Dirichlet convolution
- ABAP implementation publishes restful services for external invocation example
- SAP CR transmission request sequence and dependency check
- SAP pi / PO function operation status monitoring and inspection
- Setnx command execution failed due to full redis memory
猜你喜欢

構建元宇宙時代敏捷制造的九種能力

自定义登录失败处理
![[untitled]](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)
[untitled]

ABAP implementation publishes restful services for external invocation example

工业元宇宙平台规划与建设

Redis exception read error on connection solution

Career planning and implementation in the era of meta universe

failureForwardUrl与failureUrl

2022年广东省安全员A证第三批(主要负责人)考试试题及答案

SAP excel has completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.
随机推荐
通过流式数据集成实现数据价值(3)- 实时持续数据收集
Introduction to graph theory -- drawing
Less than 100 secrets about prime numbers
[untitled]
实践六 Windows操作系统安全攻防
2022年上海市安全员C证考试题库及答案
Yarn资源调度器
Redis exception read error on connection solution
Setnx command execution failed due to full redis memory
SAP excel has completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.
一文读懂PlatoFarm新经济模型以及生态进展
Expansion of number theory Euclid
AI上推荐 之 MMOE(多任务yyds)
使用IDEA开发Spark程序
Pyqt5与通信
Odoo 服务器搭建备忘
通过流式数据集成实现数据价值(5)- 流分析
2022年流动式起重机司机考试题库模拟考试平台操作
Understand scope
Go语言实践模式 - 函数选项模式(Functional Options Pattern)