Given a binary search tree, write a functionkthSmallest
to find thekth smallest element in it.
Note:
You may assume k is always valid, 1 ? k ? BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Recursive Code with InOrder Traversal(Accepted):
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
def inorder(root,result=[]):
if root.left: inorder(root.left,result)
result.append(root.val)
if root.right: inorder(root.right,result)
return result
result = inorder(root)
return result[k-1]