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