我刚刚从'HackerRank'中遇到过这个问题。 BST
表包含两列,分别为N
和P
。 N
代表节点,P
代表家长:Oracle中的树层次结构
N P
-- --
1 2
3 2
6 8
9 8
2 5
8 5
5 null
样本输出应该是:
1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf
我曾尝试是:
select N,
case
when level = 3 then 'leaf'
when level = 2 then 'inner'
else 'root'
end
from BST
start with P is NULL
connect by P = prior N
order by N;
虽然给出正确的结果,我对代码的硬编码不太满意(不管它应该是叶,内部还是根)。此外,如果树中存在多个层次结构,此代码将失败。
有人可以建议任何其他优雅的方式来编写相同的代码,以便它不会失败的多层次?
嗨!如果有人知道任何好的SQL挑战网站,请让我知道 – joe