본문 바로가기
코딩테스트/SQL

[LeetCode][MySQL] Tree Node

by 포뇨j 2024. 1. 3.

https://leetcode.com/problems/tree-node

 

Tree Node - LeetCode

Can you solve this real interview question? Tree Node - Table: Tree +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | p_id | int | +-------------+------+ id is the column with unique values for this table. Each row of this

leetcode.com

 

select distinct a.id, (
    case when a.p_id is null then 'Root'
    when b.p_id is null then 'Leaf'
    else 'Inner' end) as type
from tree a left join tree b on a.id = b.p_id

 

부모 노드가 없는 경우 Root, 자식 노드가 없는 경우 Leaf, 부모 노드와 자식 노드 모두 있을 경우 Inner로 처리하는 문제이다.

각 조건을 case 조건문으로 처리했다.