Skip to content

Instantly share code, notes, and snippets.

@matthewpoer
Created June 29, 2018 13:12
Show Gist options
  • Select an option

  • Save matthewpoer/f98cb12d8328e337cc315d42a9c36c7f to your computer and use it in GitHub Desktop.

Select an option

Save matthewpoer/f98cb12d8328e337cc315d42a9c36c7f to your computer and use it in GitHub Desktop.
Answer to HackerRank's "Binary Tree Nodes" SQL practice problem
-- https://www.hackerrank.com/challenges/binary-search-tree-1/problem
select
parents.n,
case
-- if there is no parent to this node, then it is the root of the tree
when parents.p is null then 'Root'
-- if there are no children to this node, then it is a leaf
when children.nodes is null then 'Leaf'
-- otherwise it much be a branch
else 'Inner'
end as word
from bst parents
left join (
select count(n) nodes, p parent from bst group by parent order by parent
) as children on children.parent = parents.n
order by parents.n;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment