简体   繁体   English

需要找到叶子节点、内部节点和根节点

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

I am trying to solve this question which is on hacker rank我正在尝试解决这个黑客级别的问题

I got the desired output but not accepted by hacker rank我得到了想要的 output 但未被黑客等级接受

Input:输入:

输入

Output: Output:

输出

My trial 1:我的试验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;

My trial 2:我的试验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;

My above querys gives me desired output but not accepted我上面的查询给了我想要的 output 但不被接受

can some one figure it out why so?有人能弄清楚为什么会这样吗?

please explain me how to solve this kind of binary tree questions and any trick to solve it请解释一下如何解决这种二叉树问题以及解决它的任何技巧

Finally after lots of trial able to write perfect query终于经过大量的试验能够写出完美的查询

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;

Please if you have any other method to solve it share it如果您有其他解决方法,请分享

I assume this is meant to test your understanding of Oracle "connect by" queries, rather than standard joins.我认为这是为了测试您对 Oracle “连接方式”查询的理解,而不是标准连接。 Roots can be identified by null parent, leafs are detected by the connect_by_isleaf pseudocolumn, and all other nodes are "inner".根可以由null父标识,叶子由connect_by_isleaf伪列检测,所有其他节点都是“内部”。 So, the query can be written like this:所以,查询可以这样写:

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