Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

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.

Example 1:

1
2
Input: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:

1
2
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

inorder讓數列保持大小順序

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
# 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

T:O(n), S:O(n), inorder sorted

class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
ans = []
if not root: return

def inorder(node):
if not node or len(ans) == k: return

inorder(node.left)
if len(ans)<k:
ans.append(node.val)
inorder(node.right)
else: return

inorder(root)
return ans[-1]

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels