230. Kth Smallest Element in a BST

2021. 5. 7. 09:46·Algorithm
 

Kth Smallest Element in a BST - LeetCode

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

1. In-Order Traversal using Iteration

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        answers=[]
        def inorder(cur):
            global count
            if not cur:
                return
            inorder(cur.left)
            answers.append(cur.val)
            inorder(cur.right)
            
        inorder(root)
        return answers[k-1]

이진 탐색 트리는 in-order로 순회하면 오름차순으로 정렬된 값을 얻을 수 있다.

 

2. In-Order Traversal using Stack

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        stack, count = [], 0
        while True:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            count += 1
            if count == k:
                return root.val
            root = root.right

in-order 순회는 stack으로도 구현이 가능하다.

'Algorithm' 카테고리의 다른 글

347. Top K Frequent Elements  (0) 2021.05.08
647. Palindromic Substrings  (1) 2021.05.07
739. Daily Temperatures  (0) 2021.05.06
78. Subsets  (2) 2021.05.06
1. Two Sum  (0) 2021.05.05
'Algorithm' 카테고리의 다른 글
  • 347. Top K Frequent Elements
  • 647. Palindromic Substrings
  • 739. Daily Temperatures
  • 78. Subsets
Doljae
Doljae
  • Doljae
    Zero to Hero
    Doljae
  • 전체
    오늘
    어제
    • 분류 전체보기 (349)
      • Programming (54)
      • Algorithm (161)
      • Review (102)
      • Career (8)
      • Diary (18)
      • Shorts (4)
      • Temp (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글 쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    sql튜닝
    나는리뷰어다
    database
    인프콘
    db
    2021
    ChatGPT
    한빛미디어
    프로그래머스
    leetcode
    2023
    line
    java
    컨퍼런스
    백준
    코딩테스트
    회고
    나는 리뷰어다
    AI
    mysql
    개발자
    jpa
    BOJ
    라인
    공채
    PYTHON
    면접
    코딩
    2022
    sql
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Doljae
230. Kth Smallest Element in a BST
상단으로

티스토리툴바