我正在解决hackerranks二叉树问题.PFB的问题
您将获得一个表BST,其中包含两列:N和P,其中N表示二进制树中节点的值,P是N的父节点.
编写查询以查找按节点值排序的二叉树的节点类型.为每个节点输出以下内容之一:
Root: If node is root node.
Leaf: If node is leaf node.
Inner: If node is neither root nor leaf node.
Run Code Online (Sandbox Code Playgroud)
我能够使用以下查询解决这个问题
select n,
case
when p is null then 'Root'
when p is not null and (n in (select p from BST)) then 'Inner' else 'Leaf'
end
from BST order by n
Run Code Online (Sandbox Code Playgroud)
但在此之前,我正在尝试以下查询无法正常工作
select n,
case
when p is null then 'Root'
when p is not null and (n in (select p from BST)) then 'Inner'
when p is not null and (n not in (select p from BST)) then 'Leaf'
end
from BST order by n
Run Code Online (Sandbox Code Playgroud)
上面的查询给出了根音符和内部节点但是它没有叶子给出null,有人可以解释为什么它显示这种行为.
你可以在这里试试这个问题
谢谢
这是因为sql的处理方式IN
和NOT IN
查询方式有关。
NOT IN
计算!=
列表中每个元素的子句,并且列表(p 列)包含NULL
值。因此, value != NULL 的计算结果为 UNKNOWN。
尝试这个:
select n,
case
when p is null then 'Root'
when p is not null and (n in (select p from BST)) then 'Inner'
when p is not null and (n not in (select p from BST where p IS NOT null)) then 'Leaf'
end
from BST order by n
Run Code Online (Sandbox Code Playgroud)
这应该会产生预期的结果。
归档时间: |
|
查看次数: |
252 次 |
最近记录: |