簡體   English   中英

需要找到葉子節點、內部節點和根節點

[英]need to find leaf , inner and root node

我正在嘗試解決這個黑客級別的問題

我得到了想要的 output 但未被黑客等級接受

輸入:

輸入

Output:

輸出

我的試驗1:

with tb1 as
(
   select N,P from binary_tree
), tb2 as 
(
   select N,P from binary_tree
)
select t2.N as t2_N,
case 
     when t2.P is null and t1.P is null  and t1.N is null then 'root'
     when t2.P is not null and t1.P is null and t1.N is not null then 'inner'
     ELSE 'leaf'
end as RESULT
from tb2 t2 LEFT JOIN tb1 t1 ON t2.P = t1.N order by t2.N;

我的試驗2:

with tb1 as
(
   select N,P from BST
), tb2 as 
(
   select P from BST
)
select distinct t.* from (select t1.N as tn,
case 
    when t1.N is not null and t2.P is not null and t1.P is null then 'root'
    when t1.N is not null and t2.P is not null and t1.P is not null then 'inner'
    when t1.N is not null and t2.P is null and t1.P is not null then 'leaf'
end as RESULT
from tb1 t1 LEFT JOIN tb2 t2 on t1.N = t2.P) t order by tn;

我上面的查詢給了我想要的 output 但不被接受

有人能弄清楚為什么會這樣嗎?

請解釋一下如何解決這種二叉樹問題以及解決它的任何技巧

終於經過大量的試驗能夠寫出完美的查詢

with tb1 as
(
   select N,P from BST
), tb2 as 
(
   select P from BST
)
select distinct t.* from (select t1.N as tn,
case 
    when t1.N is not null and t2.P is not null and t1.P is null then 'Root'
    when t1.N is not null and t2.P is not null and t1.P is not null then 'Inner'
    when t1.N is not null and t2.P is null and t1.P is not null then 'Leaf'
end as RESULT
from tb1 t1 LEFT JOIN tb2 t2 on t1.N = t2.P) t order by tn;

如果您有其他解決方法,請分享

我認為這是為了測試您對 Oracle “連接方式”查詢的理解,而不是標准連接。 根可以由null父標識,葉子由connect_by_isleaf偽列檢測,所有其他節點都是“內部”。 所以,查詢可以這樣寫:

select  n,
        case when p is null             then 'Root'
             when connect_by_isleaf = 1 then 'Leaf'
             else                            'Inner' end as result
from    binary_tree
start   with p is null
connect by p = prior n
order   by n  --  if needed
;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM