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

相关推荐
蟹至之16 小时前
【MySQL】事务
数据库·mysql·事务
ao_lang16 小时前
数据库范式
数据库·mysql
DBA圈小圈16 小时前
【KingbaseES】V8R6查询长事务语句
数据库·postgresql·database
子超兄16 小时前
MVCC机制简介
数据库·mysql
虹科网络安全16 小时前
艾体宝洞察 | 在 Redis 之上,聊一聊架构思维
数据库·redis·架构
yuguo.im17 小时前
如何查看 Mysql 版本
数据库·mysql
中年程序员一枚17 小时前
让postman调用python的开发接口,链接sqlite数据库,让前后联动起来
数据库·python·postman
weixin_4624462317 小时前
解决MongoDB官网下载过慢问题
数据库·mongodb
青蛙大侠公主17 小时前
Spring事务
java·数据库·spring
老华带你飞17 小时前
校务管理|基于springboot 校务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring