简体   繁体   English

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

[英]Classifying binary tree nodes using SQL

I am trying to solve the problem mentioned at the below link我正在尝试解决以下链接中提到的问题

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

I have written the following code.Please help me where i am going wrong我已经编写了以下代码。请帮助我哪里出错了

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

Where should i modify the above code to work.我应该在哪里修改上面的代码才能工作。 Sure there are other concise codes for the same problem but please help me with this code for learning purpose.当然还有其他针对同一问题的简洁代码,但请帮助我使用此代码以供学习。

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

Result:结果:

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

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

You need to find the child instead of the higher parent .您需要找到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

You can use if else to solve it as well:您也可以使用 if else 来解决它:

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;

You can use CASE statement as follows:您可以使用 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;

-- SQL SERVER working Solution -- SQL SERVER 工作解决方案

select N, case when p is null then "Root" when N in (select P from BST) THEN "Inner" Else "Leaf" end as "P" from BST ORDER BY N;选择 N,如果 p 为空,则当 N 为“根”时(从 BST 中选择 P) THEN “Inner” Else “Leaf” 以 BST ORDER BY N 中的“P”结尾;

See the below code.请参阅下面的代码。 It might be easy to comprehend.可能很容易理解。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM