Kth Smallest in BST

LeetCode

LeetCode: https://leetcode.com/problems/kth-smallest-element-in-a-bst/

Return the k-th smallest value in a BST.

1def kthSmallest(root: Optional[TreeNode], k: int) -> int:
2 stack = []
3 cur = root
4 while cur or stack:
5 while cur:
6 stack.append(cur)
7 cur = cur.left
8 cur = stack.pop()
9 k -= 1
10 if k == 0:
11 return cur.val
12 cur = cur.right
13 return -1
5
0
3
1
6
2
2
3
4
4
5
6
1
7
tree=Array(8)
k=3
Step 1 / 3
Step 1:
Do inorder traversal; each pop gives the next smallest.
Focus: select @ [0]
k=3