Given a binary search tree, write a functionkthSmallestto 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?
Hint:
Try to utilize the property of a BST.
What if you could modify the BST node's structure?
The optimal runtime complexity is O(height of BST).
# 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):
nodeVal = 0
count = 0
found = False
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
if not root:
return 0
global nodeVal
global count
global found
count = 0
nodeVal = 0
found = False
self.kthSmallHelper(root, k)
return nodeVal
#--------------------------------------------------------------------
# Do in order traversal. That will arrange items in ascending order
# Once the kth item is reached, update the global variable 'nodeVal'
# Once it returns to the caller, return nodeVal
#--------------------------------------------------------------------
def kthSmallHelper(self, root, k):
global nodeVal
global count
global found
if root == None:
return
#-----------------------------------------
# optimization step:
# once found, then try to exit the call stack
# as fast as possible
#-----------------------------------------
if found == True:
return
# Explore left child
self.kthSmallHelper(root.left, k)
#-----------------------------------------
# count till it reaches k, then return
#-----------------------------------------
count += 1
if count == k:
nodeVal = root.val
found = True
return
if found == True:
return
# Explore right child
self.kthSmallHelper(root.right, k)