Leetcode 230. Kth Smallest Element in a BST
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.寻找二叉搜索树的第k个最小的元素
比较简单的数据结构题,用前序遍历就能求解,代码如下:
递归:
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
global count, output
count = 0
output = 0
def PreInterate( root, k) :
if(root):
PreInterate(root.left, k)
global count, output
count = count + 1
#print(count, root.val)
if count == k:
output = root.val
PreInterate(root.right, k)
PreInterate(root, k)
return output
循环:
def kthSmallest(root, k):
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if k == 0:
return root.val
root = root.right