【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;

相关推荐
多弗朗皮卡丘9 小时前
MySQL表的约束
数据库·mysql
Flynn Liang13 小时前
AI Agent Redis 生产踩坑实录:13 类故障的根因、复现与调优
数据库·人工智能·redis·缓存·ai agent·故障分析
SelectDB14 小时前
开源日志平台怎么选?ELK、Loki、ClickHouse、Apache Doris 四大方案对比与选型指南
数据库
SelectDB14 小时前
ELK 磁盘空间不足怎么办?Elasticsearch 存储膨胀原因、排查步骤与 3 种降本方案
数据库
满小满14 小时前
为什么我先 ANALYZE,而不是先加索引
数据库·dba
SelectDB15 小时前
日志分析用什么数据库好?Elasticsearch、ClickHouse、Doris 选型对比与 3 个企业案例
数据库
inferno17 小时前
十三、存储过程(PROCEDURE)
数据库·sql·mysql
数据库急诊室_阿哲17 小时前
一周慢查询日志审计:1200 条里有多少真问题
运维·数据库·dba
zhangjw3418 小时前
2-4 集合运算 union /union all /intersect/except
数据库·postgresql
Decay__18 小时前
PostgreSQL DBA 日常运维手册 —— 会话、锁阻塞、慢查询、膨胀与每日巡检
运维·数据库·sql·postgresql