230. Kth Smallest Element in a BST
- Kth Smallest Element in a BST python solution
题目描述
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

解析
因为是二叉搜索树,那么节点值的大小已经排好序了,左子树小于根节点小于右子树。所以我们只需进行一次DFS,将所有节点的值记录下来,这些节点值已经排好序了,我们只需要输出第k个即可。
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
count=[]
self.helper(root,count)
return count[k-1]
def helper(self,node,count):
if not node:
return
self.helper(node.left,count)
count.append(node.val)
self.helper(node.right,count)
Reference
https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63660/3-ways-implemented-in-JAVA-(Python)%3A-Binary-Search-in-order-iterative-and-recursive
本文介绍了一种在二叉搜索树中查找第K小元素的有效算法。通过深度优先搜索(DFS)遍历树,利用二叉搜索树的特性,即左子树的所有节点小于根节点,右子树的所有节点大于根节点,可以得到一个已排序的节点值列表。文章详细解释了如何实现这一算法,并提供了Python代码示例。
260

被折叠的 条评论
为什么被折叠?



