Subham Sikdar
Subham Sikdar

Reputation: 1

Hackerrank Binary Tree Nodes SQL solution. Please explain

I'm trying to understand why the value of n = 5(from the image link e.g.) is not reported as Inner? Since second line of case query states to check n in every distinct p. So if n = 5 which is in p shouldn't it be reported as Inner? Is it because every second line case query is re checked by first line of case query??

SELECT CASE
    WHEN P IS NULL THEN CONCAT(N, ' Root')
    WHEN N IN (SELECT DISTINCT P FROM BST) THEN CONCAT(N, ' Inner')
    ELSE CONCAT(N, ' Leaf')
    END
FROM BST
ORDER BY N;

enter image description here

enter image description here

Upvotes: 0

Views: 553

Answers (1)

trincot
trincot

Reputation: 351029

A SELECT CASE expression will result in the evaluation of at most one THEN expression -- the first one that has a WHEN condition that satisfies.

Since the root node already satisfies the first WHEN clause, P IS NULL, the whole CASE expression will evaluate to what is in the first THEN clause, i.e. CONCAT(N, ' Inner'). In this case the rest of the CASE expression is not evaluated, even though the next WHEN condition would also be true.

Upvotes: 1

Related Questions