Kth Smallest Element in BST
Problem
Given a binary search tree, write a function kthSmallest
to find the kth smallest element in it.
Solution
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.s = None
self.visited = 0
self.helper(root, k)
return self.s
def helper(self, root,k):
if root is None:
return
self.helper(root.left,k)
self.visited +=1
if k == self.visited:
self.s = root.val
return
self.helper(root.right, k)
#For any problems with inOrder traversal, in the
#recursive method we have to traverse all the way
#left before we do any operations
#We are using inOrder traversal approach
#We are keeping count of the nodes visited and
#comparing this to our input k
#Time: O(h) where h is the height of the tree
#Space: O(h) because of call stack
Last updated
Was this helpful?