Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions kth-smallest-element-in-a-bst/parkhojeong.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

kth-smallest-element-in-a-bst/parkhojeong.py
# 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 = right
class Solution:
    def kthSmallest(self, root: TreeNode | None, k: int) -> int:
        arr = []

        def inorrder(node: TreeNode):
            if node.left:
                inorrder(node.left)

            arr.append(node.val)

            if node.right:
                inorrder(node.right)

        inorrder(root)
        return arr[k - 1]
  • 패턴: Binary Search, Hash Map / Hash Set, Binary Search
  • 설명: 주어진 코드는 이진 탐색 트리의 중위 순회를 통해 정렬된 결과를 얻고, 그 중 k-1번째를 반환합니다. 중위 순회 자체는 트리 구조를 다루지만 핵심 아이디어는 이진 탐색 트리의 정렬 특성을 이용하는 패턴으로 볼 수 있습니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n)
Space O(n)

피드백: 중위 순회를 이용해 모든 노드를 방문하고 배열에 저장하므로 시간은 선형이며 추가 공간은 저장된 노드 수에 비례한다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 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 = right
class Solution:
def kthSmallest(self, root: TreeNode | None, k: int) -> int:
arr = []

def inorrder(node: TreeNode):
if node.left:
inorrder(node.left)

arr.append(node.val)

if node.right:
inorrder(node.right)

inorrder(root)
return arr[k - 1]
29 changes: 29 additions & 0 deletions lowest-common-ancestor-of-a-binary-search-tree/parkhojeong.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🏷️ 알고리즘 패턴 분석

lowest-common-ancestor-of-a-binary-search-tree/parkhojeong.py
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':

        def search(node: TreeNode, target: int):
            stack = [node]
            arr = []
            while stack:
                node = stack.pop()
                arr.append(node)
                if node.val > target:
                    stack.append(node.left)
                elif node.val < target:
                    stack.append(node.right)

            return arr

        arr1 = set(search(root, p.val))
        arr2 = search(root, q.val)

        for node in arr2[::-1]:
            if node in arr1:
                return node
  • 패턴: Binary Search, Depth-First Search, Hash Map / Hash Set
  • 설명: BST에서 특정 값의 위치를 찾는 방식으로 루트에서 자식 방향을 탐색하며, 두 노드의 LCA를 찾기 위해 경로를 추적하고 교집합을 확인하는 흐름이 주로 Binary Search와 DFS의 혼합 형태로 보이며, 경로 비교를 위해 해시 집합을 사용합니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(h)
Space O(h)

피드백: 스택 기반으로 순회하며 검색하는 방식이 필요하지 않다. BST의 특성을 활용해 루트-노드 방향으로 비교하면 더 간결하고 안전하다.

개선 제안: 고려해볼 만한 대안: BST의 특성을 이용해 루트에서 시작해 p.val과 q.val의 대소를 비교하며 자식을 따라가면 된다. 불필요한 중복 탐색 제거.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':

def search(node: TreeNode, target: int):
stack = [node]
arr = []
while stack:
node = stack.pop()
arr.append(node)
if node.val > target:
stack.append(node.left)
elif node.val < target:
stack.append(node.right)

return arr

arr1 = set(search(root, p.val))
arr2 = search(root, q.val)

for node in arr2[::-1]:
if node in arr1:
return node
Loading