SQL query classifying types of nodes in a binary tree
1
vote
1
answer
503
views
I am using MySQL in trying to solve a problem relating to a SQL query classifying types of nodes in a binary tree .
Specifically, the question states as follows:
> You are given a table, BST, containing two columns: N and P, where N represents the value of a node in Binary Tree, and P is the parent of N. Both columns have datatype as integer. Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each node:
>
> - Root: If node is root node.
> - Leaf: If node is leaf node.
> - Inner: If node is neither root nor leaf node.
Here is my attempt so far:
SELECT N,
CASE
WHEN bst_outer.P IS NULL THEN "Root"
WHEN NOT EXISTS(SELECT bst_inner.N FROM BST bst_inner WHERE bst_inner.P = bst_outer.P) THEN "Leaf"
ELSE 'Inner'
END
FROM BST bst_outer;
The output after running the above query gives incorrect result, as there appears to be no nodes with Leaf
classification. It seems like that the error lies on my second WHEN
statement, but I am not sure how to fix it.
Asked by Squirrel-Power
(111 rep)
Jan 6, 2024, 09:45 PM
Last activity: Jul 25, 2025, 05:07 PM
Last activity: Jul 25, 2025, 05:07 PM