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

相关推荐
zmzmzmalo3 小时前
Linux ELF文件加载与内存管理揭秘
linux·网络·数据库
Super 含10 小时前
Android 启动优化(五):线程、GC 与 IO 为什么会拖慢启动?
java·服务器·数据库
ltl10 小时前
向量检索引擎选型:决策树、RAG 回链与开放问题
数据库
坚持学习前端日记10 小时前
Python SQLAlchemy ORM 从0到1精通实战手册(基础到复杂高阶)
数据库·python·oracle
灯澜忆梦10 小时前
【MySQL17】进阶篇 | InnoDB引擎
数据库·mysql
anxiao_m11 小时前
2026制造业云桌面选型攻略,不同生产场景适配方案汇总
大数据·网络·数据库
许彰午11 小时前
# 数据库配拦截器,不用改BPMN
数据库
lv__pf11 小时前
redis【msb 2026金三银四redis上】
数据库·redis·缓存
布莱克60512 小时前
理解数据库聚簇索引:原理、优势与适用场景
数据库·mysql