-
608. 树节点 - 力扣(LeetCode)
-
目标
-
输入
输入:
Tree table:id p_id 1 2 1 3 1 4 2 5 2 -
输出
输出: id type 1 Root 2 Inner 3 Leaf 4 Leaf 5 Leaf
-
-
分析
树中的每个节点可以是以下三种类型之一:
"Leaf":节点是叶子节点。
"Root":节点是树的根节点。
"lnner":节点既不是叶子节点也不是根节点。
编写一个解决方案来报告树中每个节点的类型。输入:
Tree table:输出: id p_id id type 1 1 Root 2 1 2 Inner 3 1 3 Leaf 4 2 4 Leaf 5 2 5 Leaf 条件判断:1.p_id为空则为root,2.p_id不为空且id在p_id中为inner,其余为leaf id type 1 Root 2 Inner 3 Leaf 4 Leaf 5 Leaf -
实现
Create table If Not Exists Tree (id int, p_id int); Truncate table Tree; insert into Tree (id, p_id) values ('1', NULL); insert into Tree (id, p_id) values ('2', '1'); insert into Tree (id, p_id) values ('3', '1'); insert into Tree (id, p_id) values ('4', '2'); insert into Tree (id, p_id) values ('5', '2'); SELECT * FROM Tree; SELECT id,CASE WHEN p_id IS NULL THEN 'Root' WHEN p_id IS NOT NULL AND id in (SELECT p_id FROM Tree)THEN 'Inner' ELSE 'Leaf' END type FROM Tree;
-
小结
使用CASE...WHEN条件查询
标签:insert,into,Tree,608,id,力扣,values,LeetCode,节点 From: https://blog.csdn.net/2301_78665414/article/details/144570049