[LeetCode]Kth Smallest Element in BST

2024. 3. 23. 15:59·SW개발/코딩테스트

https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제 분석

주어진 Binary Search Tree에서 K번째로 작은 숫자를 찾는 문제입니다.

 

처음 시도한 답안 

# 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: Optional[TreeNode], k: int) -> int:
        output = []

        def dfs(root):
            if not root:
                return
            
            dfs(root.left)
            
            if len(output) >= k:
                return

            output.append(root.val)
            dfs(root.right)

        dfs(root)

        return output[-1]

접근 방법

  1. DFS를 활용해 트리를 탐색합니다.
  2. Binary Search Tree의 특성을 이용해 중위 순회합니다.
    1. BST의 경우 왼쪽 자식 - 부모 - 오른쪽 자식 순서대로 값이 증가합니다.
    2. 중위 순회역시 왼쪽 자식 - 부모 -오른쪽 자식 순서대로 탐색하기 때문에 k번째로 작은수를 찾을 수 있습니다.
    3. 중위 순회를 진행하면서 output에 담긴 갯수가 k보다 같거나 크면 함수를 종료합니다.
    4. output의 마지막 요소가 k번째로 작은 요소가 됩니다.

BST 특성과 중위 순회의 특성이 k번째로 작은 요소를 구할 수 있는 힌트가 되기 때문에 중위 순회를 응용했습니다.

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Find the Duplicate Number  (2) 2024.03.25
[LeetCode]Search a 2D Matrix II  (0) 2024.03.24
[Leetcode]Kth Largest Element in an Array  (0) 2024.03.22
[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal  (0) 2023.06.02
[LeetCode]Binary Tree Level Order Traversal  (0) 2023.06.01
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Find the Duplicate Number
  • [LeetCode]Search a 2D Matrix II
  • [Leetcode]Kth Largest Element in an Array
  • [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    라이프 스타일
    배공파용
    어플리케이션
    오픈소스
    플레이스토어
    Contributor
    컨트리뷰터
    트리 #AVL #알고리즘 #자료구조
    배달
    음식
    g
    배달비 공유
    django
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Kth Smallest Element in BST
상단으로

티스토리툴바