Kth smalles element in 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)Last updated