티스토리 뷰

문제 링크

 

Kth Smallest Element in a BST - LeetCode

Can you solve this real interview question? Kth Smallest Element in a BST - Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.   Example 1: [https://assets.leetco

leetcode.com

풀이

# 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, k: int) -> int:
        # 중위 순회 함수(왼쪽끝->오른쪽끝 순서)
        def left_to_right(node):
            if not node:
                return []
            return left_to_right(node.left) + [node.val] + left_to_right(node.right)
        
        # 루트 노드 입력 -> 오름차순 정렬된 원소 리스트
        inorder = left_to_right(root)
        # 중위 순회 결과에서 인덱스가 k - 1인 원소 = k번째로 작은 원소
        return inorder[k - 1]