Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Dynamic Programmin
- list of list
- 김태강
- 삼성인 아마조니언 되다
- technical debt
- mysql #numa #swap #memory
- 독후감
- 와썹맨
- Python
- 동적 프로그래밍
- 리트코드
- 트리
- 기술적 채무
- minimum path sum
- 아마조니언
- 파이썬
- Unique Paths
- LongestPalindromicSubstring
- 리스트의 리스트
- 알고리즘
- 그거봤어?
- 삼성역량테스트
- 규칙없음
- No Rules Rules
- leetcode
- 프로그래머스
- BFS
- Envoy
- 블린이
- 나는 아마존에서 미래를 다녔다
Archives
- Today
- Total
개발자가 되고 싶은 준개발자
[LeetCode] 230. Kth Smallest Element in a BST 문제 및 풀이 코드 본문
문제
Given the root of a binary search tree, and an integer k, return the kth (1-indexed) smallest element in the tree.
BST가 주어졌을 때 K번째로 작은 수를 찾아라.
코드
BST 문제의 경우 우선 순회를 어떤 식으로 할지 정해야 한다.
순회의 방식에는 inorder(left->root->right), postorder(left->rightt->root), preorder(root->left->right) 세가지의 경우가 있다.
이 문제에서는 K번째 수를 찾으라 했으니 순회를 했을때 정렬이 되는 방법을 택하는 게 좋을 듯 하다. 따라서 inorder를 택했다.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
def inorder(r):
return inorder(r.left) + [r.val] + inorder(r.right) if r else []
return inorder(root)[k - 1]
'알고리즘 공부 > LeetCode' 카테고리의 다른 글
[LeetCode] 7. Reverse Integer 파이썬 코드 (0) | 2021.05.29 |
---|---|
[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 풀이 및 코드 (0) | 2021.03.07 |
[LeetCode] 98. Validate Binary Search Tree 풀이 및 코드 (0) | 2021.02.27 |
[LeetCode] 100. Same Tree 풀이 및 코드 (1) | 2020.09.26 |
[LeetCode] 103. Binary Tree Zigzag Level Order Traversal 풀이 및 코드 (1) | 2020.09.26 |