1 """ 2 Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 3 Note: 4 You may assume k is always valid, 1 ≤ k ≤ BST's total elements. 5 Example 1: 6 Input: root = [3,1,4,null,2], k = 1 7 3 8 / \ 9 1 4 10 \ 11 2 12 Output: 1 13 Example 2: 14 Input: root = [5,3,6,2,4,null,null,1], k = 3 15 5 16 / \ 17 3 6 18 / \ . 19 2. 4 20 is / 21 is . 1 22 is the Output:. 3 23 is "" " 24 " "" 25 stack preorder used, plus a determination statement 26 is IF len (RES) == K 27 "" " 28 # Definition for binary Tree A . Node 29 # class the TreeNode: 30 # DEF the __init __ (Self, X): 31 is # self.val X = 32 # self.left = None 33 is # self.right None = 34 is 35 class Solution: 36 DEFkthSmallest (Self, the root, K): 37 [ Stack = [] 38 is RES = [] 39 CUR = the root 40 the while Stack or CUR: 41 is IF CUR: 42 is stack.append (CUR) 43 is CUR = cur.left 44 is the else : 45 = CUR stack.pop () 46 is res.append (Cur.Val) 47 IF len (RES) == K: # traversal sequence, determines the middle of a sentence 48 return RES [-1 ] 49 cur = cur.right