This was asked to me in a recent interview. Binary tree is stored in database in the following schema
Table tree ( int nodeId, int parentId, int data)
This is a self referencing table. I was asked to write query to print the data of all nodes in the path from the root to the given node. Is it possible to do it in one query?
The solution I gave was loading all the rows to a hashMap with key as nodeId and value as parentId and print the path to the root from the given node using the map.
I can write nested queries to print this if I know the depth of the node in the binary tree. Sample query to print all the nodes from root to a node with nodeId='4' which is at depth 2 is as follows: "select n.data, n1.data, n2.data from Tree n where nodeId in (select parentId from Tree n1 where nodeId in (select pId from Tree n2 where nodeId='4')); "
Is it possible to do this without using nested queries? If so what query I can use to do this?