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

相关推荐
上学的小垃圾7 小时前
01-数据库系统概述
数据库
二进制漫游记7 小时前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding
2501_928996227 小时前
GPT-4o换DeepSeek迁移成本多少?中科热备解析API聚合平台技术账本
前端·数据库·人工智能
泡干脆面就番茄10 小时前
MySQL_子查询_分页查询与联合查询详解
数据库·mysql
devpotato11 小时前
缓存与数据库更新顺序不一致问题
java·数据库·redis
天若有情67311 小时前
Node+MySQL小型全栈笔记项目实战课程分享
数据库·笔记·mysql
wxwx_bscxy32211 小时前
基于springboot宠物领养系统的设计与实现
数据库·spring boot·后端·spring·宠物
九月要晚安12 小时前
达梦DW与AFC对比
数据库
实战派K8S&DB12 小时前
如何在内网配置 TiDB 数据库 Agent
数据库·人工智能·分布式·tidb
实战派K8S&DB12 小时前
《基于 Dify + FastAPI + PyTiDB 搭建大模型驱动的 TiDB 智能运维 Agent》
运维·数据库·分布式·云原生·tidb·fastapi