[Leetcode] 230. Kth Smallest Element in a BST
inorder traversal + recursive
Time Complexity:
Space Complexity:
# 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 __init__(self):
self.i = 0
self.res = None
def kthSmallest(self, root: TreeNode, k: int) -> int:
def inorder(head: TreeNode):
if head is not None and self.i < k:
inorder(head.left)
self.i += 1
if self.i == k: self.res = head.val
inorder(head.right)
inorder(root)
return self.res
inorder traversal + iterative
Time Complexity:
Space Complexity:
class Solution:
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
stack = []
while True:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if not k:
return root.val
root = root.right
Author And Source
이 문제에 관하여([Leetcode] 230. Kth Smallest Element in a BST), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@haebin/Leetcode-230.-Kth-Smallest-Element-in-a-BST저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)