LeetCode/Grind169 60

232. Implement Queue using Stacks ☆

232. Implement Queue using Stacks 이 문제는 두 개의 스택을 이용해서 큐(FIFO)를 구현하는 문제로, 인터뷰에서도 자주 나오는 고전 문제입니다.Follow-up 조건인 "모든 연산의 시간복잡도가 평균 O(1)" 도 만족해야 합니다.✅ 핵심 아이디어두 개의 스택 사용:in_stack: push() 할 때 사용하는 스택 (뒤쪽에 쌓임)out_stack: pop()/peek() 할 때 사용하는 스택 (앞쪽에서 꺼냄)📌 필요할 때만 in_stack을 out_stack으로 옮기기 때문에 amortized O(1) 시간 보장됨✅ 구현 코드 (Python, 리스트를 스택처럼 사용)class MyQueue: def __init__(self): # 데이터를 입력받는 스택 ..

LeetCode/Grind169 2025.04.22

110. Balanced Binary Tree ☆

110. Balanced Binary Tree✅ 정답 접근 방식모든 서브트리에서 좌우 높이 차가 1 이하여야 함재귀적으로 하향하면서, 각 노드의 서브트리 균형 여부까지 함께 체크해야 함보통은 dfs() 함수에서 높이(height)를 리턴하면서, 불균형이면 특수값(-1 등)을 리턴하는 방식이 깔끔해요최종 코드🔧 정답 코드 (DFS 방식, 높이와 균형 여부 동시에 판단)# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclass..

LeetCode/Grind169 2025.04.22

235. Lowest Common Ancestor of a Binary Search Tree ☆

235. Lowest Common Ancestor of a Binary Search Tree # Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': # 바이너리 서치 트리 BST 에서 가장 가까운 조상 찾기 # BST 이므로, 왼쪽에 있으면 무조건 작은값, 오른..

LeetCode/Grind169 2025.04.22