Kth Smallest Element in a BST
Input:
root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output:
1Input:
root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output:
3Last updated
Input:
root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output:
1Input:
root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output:
3Last updated
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
res = None
def helper(root):
nonlocal res,k
# if not root:
# return
if root.left:
helper(root.left)
k -= 1
if k == 0 :
res = root.val
return
if root.right:
helper(root.right)
helper(root)
return res# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
stack = []
cur = root
while cur or stack: #错在Not stack...
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
k -= 1
if not k:
return cur.val
cur = cur.right