LeetCode 230. 二叉搜索树中第K小的元素
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 1
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法:
1:
# 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:
list=[]
def add(node):
nonlocal list
if not node:
return
else:
list.append(node.val)
add(node.left)
add(node.right)
add(root)
return sorted(list)[k-1]
2:
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
def Count(root: TreeNode) -> int:
if not root:
return 0
return Count(root.left)+Count(root.right)+1
leftCount = Count(root.left)
if leftCount == k-1:
return root.val
elif leftCount > k-1:
return self.kthSmallest(root.left,k)
else:
return self.kthSmallest(root.right,k-leftCount-1)