티스토리 뷰
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]
'개발자를 위한 한 걸음 > 코딩 문제' 카테고리의 다른 글
인구 이동 - 백준 #16234, 골드5, 구현/그래프/너비우선탐색/시뮬레이션 (0) | 2023.04.14 |
---|---|
연속합 - 백준 #1912, 실버2, 다이나믹 프로그래밍 (0) | 2023.04.09 |
Palindromic Substrings - LeetCode #647 (0) | 2023.04.06 |
빛의 경로 사이클 - 프로그래머스 lv.2 (0) | 2023.04.06 |
거리두기 확인하기 - 프로그래머스 lv.2 (0) | 2023.04.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 카카오 코딩테스트
- 실버2
- 너비 우선 탐색
- 브루트포스 알고리즘
- 리트코드
- 문자열
- 카카오
- 정렬
- 백준
- Python
- 구현
- lv.2
- 실버3
- 프로그래머스
- 코딩 테스트
- 그리디 알고리즘
- 코딩테스트
- 깊이 우선 탐색
- 수학
- lv.3
- 릿코드
- 백트래킹
- Simulation
- 시뮬레이션
- 그래프 탐색
- 다이나믹 프로그래밍
- 코드트리
- leetcode
- 골드5
- 그래프 이론
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
글 보관함