使用SQL对二叉树节点进行分类

时间:2018-08-07 16:52:28

标签: mysql sql

我正在尝试解决以下链接中提到的问题

https://www.hackerrank.com/challenges/binary-search-tree-1/problem

我写了下面的代码。请帮我哪里错了

Select q.Node,case
              WHEN q.Node NOT IN q.Parent THEN 'Leaf' 
              WHEN q.Node IN q.Parent AND q.Node NOT IN q.Higher_Parent THEN 'Inner'
              WHEN q.Node IN q.Parent AND q.Node IN q.Higher_Parent THEN 'Root'
              END as NodeType
from (
SELECT B1.N as Node,B1.P as Parent,B2.P as Higher_Parent FROM 
BST B1 INNER JOIN BST B2 
ON B1.P = B2.N
ORDER BY Node ASC
) q

N P HP
1 2 5
2 5 NULL
3 2 5
6 8 5
8 5 NULL
9 8 5

我应该在哪里修改以上代码以工作。当然,对于同一问题,还有其他简洁的代码,但是出于学习目的,请帮助我使用此代码。

6 个答案:

答案 0 :(得分:0)

select n.n,
  case 
    when max(p.n) is null then 'root'
    when max(c.n) is null then 'leaf'
    else 'inner'
  end as type
from bst n
left join bst p on p.n = n.p
left join bst c on c.p = n.n
group by n.n

结果:

| n |  type |
|---|-------|
| 1 |  leaf |
| 2 | inner |
| 3 |  leaf |
| 5 |  root |
| 6 |  leaf |
| 8 | inner |
| 9 |  leaf |

演示:http://sqlfiddle.com/#!9/ba3c76/1

答案 1 :(得分:0)

您需要找到child而不是higher parent

Select distinct c.n, 
        case when c.P is null then 'Root' 
             when b1.N is null then 'Leaf'
             else 'Inner' end
from BST c
left join BST b1
on c.N = b1.P
order by c.n

答案 2 :(得分:0)

您也可以使用其他方式解决该问题:

SELECT B.N, IF(B.P IS NULL, 'Root', IF((SELECT COUNT(*) FROM BST AS A WHERE A.P=B.N)>0,'Inner','Leaf')) 
FROM BST AS B 
ORDER BY B.N;

答案 3 :(得分:0)

您可以使用CASE语句,如下所示:

SELECT N, CASE WHEN P IS NULL THEN 'Root' 
WHEN(SELECT COUNT(*) FROM BST WHERE P = T.N) > 0 THEN 'Inner'
ELSE 'Leaf'
END
FROM BST T
ORDER BY N;

答案 4 :(得分:0)

-SQL SERVER工作解决方案

选择N, 案件 当p为null时,则“根” 当N in(从BST中选择P)时,则“ Inner” 其他“叶”结尾为“ P” 来自BST N排序;

答案 5 :(得分:0)

请参见以下代码。可能很容易理解。

select n, 'Leaf' as nodename from bst
where n not in (select distinct p from bst where p is not null)
union
select n, 'Root' as nodename from bst
where p is null
union
select n, 'Inner' as nodename from bst
where n in (select distinct p from bst)
and p is not null
order by n asc;