We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- SQL
- Advanced Select
- Binary Tree Nodes
- Discussions
Binary Tree Nodes
Binary Tree Nodes
Sort by
recency
|
2347 Discussions
|
Please Login in order to post a comment
select distinct cld.N , case when pr.N is null then 'Leaf' when cld.P is null then 'Root' when pr.N is not null then 'Inner' end as node_type from BST cld left join BST pr on cld.N = pr.P order by cld.N
I complicated it a little. But how do you guys think this solution looks:
if in case column (N) dosent have all the required values.
with tbl1 as (select distinct(N) from bst), tbl2 as (select distinct(P) from bst), tbl3 as ( Select N from tbl1 union Select P from tbl2), tbl4 as ( select * from tbl3 where N is not null)
Select *, Case when tbl4.N in (Select * from tbl2 where P in (select N from BST where P is not null)) then "Inner" when tbl4.N in (Select N from BST where P is null)then "Root" ELSE 'Leaf' end as node_type from tbl4 order by N
MySQL Solution:
SELECT N, CASE WHEN P IS NULL THEN 'Root' WHEN N IN (SELECT P FROM BST) THEN 'Inner' ELSE 'Leaf' END AS nodetype FROM BST ORDER BY N;