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.
select o.n, case when o.p is null then 'Root' when not exists(select * from bst where p=o.n) then 'Leaf' else 'Inner' end from bst o order by o.n
According to the docs, using exists() is much more efficient because the db stops looking after the first match. In a large table, this could have a measureable impact. NOTE: you might think that in this particular example there would not be much benefit since each node has exactly one parent, and you'd be right, except that if the column is not indexed, there is no way for the db to know that, and it would still do a full table scan.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Binary Tree Nodes
You are viewing a single comment's thread. Return to all comments →
Nearly identical in MySQL:
select o.n, case when o.p is null then 'Root' when not exists(select * from bst where p=o.n) then 'Leaf' else 'Inner' end from bst o order by o.n
According to the docs, using exists() is much more efficient because the db stops looking after the first match. In a large table, this could have a measureable impact. NOTE: you might think that in this particular example there would not be much benefit since each node has exactly one parent, and you'd be right, except that if the column is not indexed, there is no way for the db to know that, and it would still do a full table scan.