SOLUTION WITH ROWNUMBER ( SQL SERVER )
Intuition\r\n Describe your first thoughts on how to solve this problem. \r\n\r\n# Approach\r\n Describe your approach to solving the problem. \r\n\r\n# Complex
# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\n\r\n# Code\r\n```\r\n/* Write your T-SQL query statement below */\r\n\r\n\r\n\r\n;WITH CTE AS (SELECT DISTINCT\r\n\tT1.id,\r\n\t\r\n\t\tIIF(T1.p_id IS NULL, \'Root\',\r\n\t\tIIF((T2.id IS NOT NULL AND T3.id IS NULL) OR (T2.id IS NOT NULL AND T3.id IS NOT NULL) ,\'Inner\',\r\n\t\t\tIIF(T2.id IS NULL AND T3.id IS NULL  , \'Leaf\',\'Leaf\'))) type\r\nFROM\t\r\n\tTree T1\r\nLEFT JOIN\r\n\tTree T2 ON T2.p_id = T1.id\r\nLEFT JOIN\r\n\tTree T3 ON T3.p_id = T2.id\r\n)\r\n,CTE2 AS (SELECT\r\n\t*,\r\n\tROW_NUMBER() OVER(PARTITION BY id ORDER BY (SELECT NULL)) KeyID\r\nFROM\r\n\tCTE\r\n)\r\nSELECT\r\n\tid,\r\n\ttype\r\nFROM\r\n\tCTE2\r\nWHERE\r\n\tKeyID = 1\r\n```
['MS SQL Server']