LeetCode # 608. 树节点

608. 树节点

题目

表:Tree

±------------±-----+

| Column Name | Type |

±------------±-----+

| id | int |

| p_id | int |

±------------±-----+

id 是该表中具有唯一值的列。

该表的每行包含树中节点的 id 及其父节点的 id 信息。

给定的结构总是一个有效的树。

树中的每个节点可以是以下三种类型之一:

  • "Leaf":节点是叶子节点。
  • "Root":节点是树的根节点。
  • "lnner":节点既不是叶子节点也不是根节点。
    编写一个解决方案来报告树中每个节点的类型。

以 任意顺序 返回结果表。

结果格式如下所示。

示例 1:

输入:

Tree table:

±---±-----+

| id | p_id |

±---±-----+

| 1 | null |

| 2 | 1 |

| 3 | 1 |

| 4 | 2 |

| 5 | 2 |

±---±-----+

输出:

±---±------+

| id | type |

±---±------+

| 1 | Root |

| 2 | Inner |

| 3 | Leaf |

| 4 | Leaf |

| 5 | Leaf |

±---±------+

解释:

节点 1 是根节点,因为它的父节点为空,并且它有子节点 2 和 3。

节点 2 是一个内部节点,因为它有父节点 1 和子节点 4 和 5。

节点 3、4 和 5 是叶子节点,因为它们有父节点而没有子节点。

分析

单独查询,结果合并,针对节点的不同条件去查找,然后合并结果

题解

sql 复制代码
# 分步查询
# 根节点的父节点为空
-- select id, 'Root' type from tree where p_id is NULL

-- # 叶子节点没有子节点,但有父节点
-- select id, 'Leaf' type from tree where id not in (
--     # 没有子节点就是在p_id列里不存在
--     select distinct p_id from tree where p_id is not NULL
-- ) and p_id is not NULL # 并且自己有父节点

-- # 内部节点,有孩子有父亲节点
-- select id, 'Inner' type from tree where id in(
--     # 自己也要出现在p_id列作为别人的父节点
--     select distinct p_id from tree where p_id is not NULL
-- ) and p_id is not NULL

# 将分步步骤连起来
# 根节点的父节点为空
select id, 'Root' type from tree where p_id is NULL
union
# 叶子节点没有子节点,但有父节点
select id, 'Leaf' type from tree where id not in (
    # 没有子节点就是在p_id列里不存在
    select distinct p_id from tree where p_id is not NULL
) and p_id is not NULL # 并且自己有父节点
union
# 内部节点,有孩子有父亲节点
select id, 'Inner' type from tree where id in(
    # 自己也要出现在p_id列作为别人的父节点
    select distinct p_id from tree where p_id is not NULL
) and p_id is not NULL
order by id
相关推荐
莫晓燚12 小时前
阿里云若依项目部署与日志采集---实战
运维·数据库·redis·阿里云·ruoyi
香蕉大香蕉(06敬畏市场)12 小时前
MySQL 单点详解(08)
java·数据库·mysql·面试·八股
Tisfy12 小时前
LeetCode 3665.统计镜子反射路径数目:三个动态规划数组
leetcode·动态规划·代理模式·题解
l1t13 小时前
DeepSeek总结的如何在 PostgreSQL 中删除一张 4 TB 的表
数据库·postgresql
ClouGence13 小时前
开源数据库管理工具 CloudDM 发布新版本,支持团队多级审批工单,无需依赖第三方系统
数据库·sql·开源
李纲明13 小时前
WordPress 报建立数据库连接时出错:先核 wp-config 四元组,再查 MySQL 服务与表修复
运维·数据库·mysql·wordpress·排障·devdiy
海绵宝宝转agent13 小时前
LeetCode100 二叉树个人题解
算法·leetcode·深度优先
鸢尾掠地平14 小时前
MySQL之DML(含例子)
数据库·mysql
文丑颜不良啊15 小时前
LeetCode1581~1600题目解析
java·leetcode
香蕉大香蕉(06敬畏市场)15 小时前
MySQL 单点详解(06)
java·数据库·mysql·博客·实习