迭代中序遍历从最小的节点开始计数,返回第k个就是第K小的元素
def kthSmallest(self, root, k):
stack = []
while root or stack:
if root:
stack.append(root)
root = root.left
else:
tmp = stack.pop()
k -= 1
if k == 0:
return tmp.val
root = tmp.right
递归中序遍历,和迭代思路一样先找到最小的然后开始计数。返回第k个就是第k小的
def kthSmallest(self, root, k):
self.res = 0
self.count = 0
def inorder(root):
if not root:
return
inorder(root.left)
self.count += 1
if self.count == k:
self.res = root.val
return
inorder(root.right)
inorder(root)
return self.res