此题看题解,其实这道题蛮简单的,需要注意二叉搜索树左小右大,为什么还需要看题解,需要反思!
# 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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
self.count=0
self.result=None
def inorder_traversal(node):
if not node:
return
inorder_traversal(node.left)
self.count+=1
if self.count==k:
self.result=node.val
return
inorder_traversal(node.right)
inorder_traversal(root)
return self.result