【SQL每日一练】查询二进制树节点

文章目录


题目

有一个表BST,其中包含两列:N和P,其中N表示二进制树中节点的值,P是N的父级。

编写一个查询,以查找按节点值排序的二进制树的节点类型。为每个节点输出以下内容之一:

root:如果节点是根节点。

Leaf:如果节点是叶节点。

Inner:如果节点既不是根节点也不是叶节点。

输入

输出

复制代码
1 Leaf
2 Inner
3 Leaf
5 Root
6 Leaf
8 Inner
9 Leaf

一、题析

根据上面题目可知

  1. P 是 null,那对应的N就是 Root
  2. 如果P和N中有对应的值,那 就是 Inner
  3. 否则(P和N没有值)就是 Leaf

二、题解

1.MySQL/SqlServer

代码如下:

c 复制代码
select DISTINCT a.N,
case when a.P is null then 'Root'
when b.P is null then 'Leaf' 
else 'Inner' end
from BST a left join  BST  b on a.N = b.P 
order by a.N

或者

复制代码
SELECT BST.N, CASE
	WHEN BST.P IS NULL THEN 'Root' 
	WHEN Parents.P IS NULL THEN 'Leaf'
	ELSE 'Inner' END
FROM BST
LEFT JOIN (SELECT DISTINCT P FROM BST ) Parents on Parents.P=BST.N
ORDER BY BST.N

2.Oracle

复制代码
with tmp as (
  select n, p, level as l
  from   bst
  connect by prior n = p
  start with p is null
)
select n, case when l = 1 then 'Root'
            when l = (select max(l) from tmp) then 'Leaf'
            else 'Inner'
       end output
from tmp
order by n;

相关推荐
凌虚5 小时前
面向 MySQL 用户的 PostgreSQL 快速上手指南
数据库·后端·架构
五阿哥永琪6 小时前
MySQL中操作json的函数!
数据库·mysql·json
来者皆善6 小时前
了解Mysql优化吗?如何优化索引?
数据库·mysql
赤壁小虾8 小时前
【渲染流水线】[逐片元阶段]-[透明度测试]以UnityURP为例
java·前端·数据库
MC皮蛋侠客8 小时前
SQLAlchemy 系列(七):高级建模与高效写入——批量 DML、方言与扩展
数据库·python
奈斯先生Vector9 小时前
把 Midjourney 二次编辑做成生产系统:customId 能力令牌、Action Graph 与 WebUI 精修工作台
数据库·人工智能·架构·aigc·音视频·midjourney
Lethehong10 小时前
双擎并驱·全链路并行:KFS让TB级异构增量同步秒级到达
数据库
MC皮蛋侠客10 小时前
SQLAlchemy 系列(八):AsyncIO、并发与 Web 生命周期——让每个并发任务持有自己的 Session
数据库·python
一水10 小时前
Redis实战:一个AI工作流系统里的五个应用场景,从传参到限流的完整链路
数据库·redis·wpf
枫叶v.11 小时前
Prompt Injection 防不住怎么办?从 Source-Sink 模型设计 Agent 安全边界
数据库·安全·prompt