当前位置:网站首页>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
边栏推荐
- LeetCode 1249. Minimum Remove to Make Valid Parentheses - FB高频题1
- Mobius inversion
- Leetcode0587. Install fence
- Expansion of number theory Euclid
- CSP认证 202203-2 出行计划(多种解法)
- 通过流式数据集成实现数据价值(5)- 流分析
- SAP debug debug for in, reduce and other complex statements
- [CF 1425d] danger of mad snakes
- 代码源每日一题 div1 (701-707)
- P1446 [hnoi2008] cards (Burnside theorem + DP count)
猜你喜欢
Leetcode question bank 78 Subset (recursive C implementation)
[educational codeforces round 80] problem solving Report
《谷雨系列》空投
Kernel PWN learning (4) -- double fetch & 0ctf2018 baby
Alibaba cloud architects interpret the four mainstream game architectures
工业元宇宙平台规划与建设
PHP笔记(一):开发环境配置
Interviewer: let's talk about some commonly used PHP functions. Fortunately, I saw this article before the interview
SAP excel has completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.
防疫登记小程序
随机推荐
How to use SQL statement union to get another column of another table when the content of a column in a table is empty
[codeforces - 208e] blood cousins
Flutter's loading animation is more interesting
NEC infrared remote control coding description
Leetcode0587. Install fence
Solving Lucas number and combination theorem
Personal homepage software fenrus
2022年流动式起重机司机考试题库模拟考试平台操作
MapReduce核心和基础Demo
構建元宇宙時代敏捷制造的九種能力
Pyqt5 and communication
Computer network security experiment II DNS protocol vulnerability utilization experiment
Sim Api User Guide(8)
Example of data object mask used by SAP translate
杰理之有时候定位到对应地址的函数不准确怎么办?【篇】
AI上推荐 之 MMOE(多任务yyds)
理解作用域
Custom login failure handling
Redis 内存占满导致的 Setnx 命令执行失败
PHP笔记(一):开发环境配置