难度中等376收藏分享切换为英文接收动态反馈
给定一个二叉搜索树的根节点 root
,和一个整数 k
,请你设计一个算法查找其中第 k
个最小元素(从 1 开始计数)。
示例 1:
输入:root = [3,1,4,null,2], k = 1 输出:1
示例 2:
输入:root = [5,3,6,2,4,null,null,1], k = 3 输出:3
提示:
- 树中的节点数为
n
。 1 <= k <= n <= 104
0 <= Node.val <= 104
1.本思路,没用到二叉搜索树的特点
# 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: TreeNode, k: int) -> int:
res = []
def dfs(root):
res.append(root.val)
if root.left:
dfs(root.left)
if root.right:
dfs(root.right)
dfs(root)
def partition(res,left,right):
temp = res[left]
while left < right:
while left<right and res[right]>temp:
right -= 1
res[left] = res[right]
while left<right and res[left] < temp:
left += 1
res[right] = res[left]
res[left] = temp
return left
def quickSort(res,left,right):
if left >= right:
return
mid = partition(res,left,right)
quickSort(res,left,mid-1)
quickSort(res,mid+1,right)
quickSort(res,0,len(res)-1)
return res[k-1]
什么是二叉查找树:
根节点的值大于其左子树中任意一个节点的值,小于其右节点中任意一节点的值,这一规则适用于二叉查找树中的每一个节点。
本文章重点来讨论一下关于二叉查找树删除节点的问题。
所以可以用中序遍历即可求解
class Solution:
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
def inorder(r):
return inorder(r.left) + [r.val] + inorder(r.right) if r else []
return inorder(root)[k - 1]
复杂度分析
- 时间复杂度:O(N)O(N),遍历了整个树。
- 空间复杂度:O(N)O(N),用了一个数组存储中序序列。