Kth Smallest Element in a BST in Python


Suppose we have a binary search tree. We have to find the Kth smallest element in that BST. So if the tree is like −


So if we want to find 3rd smallest element, then k = 3, and result will be 7.

To solve this, we will follow these steps −

  • create one empty list called nodes

  • call solve(root, nodes)

  • return k – 1th element of nodes

  • the solve method is created, this takes root and nodes array, this will work as follows −

  • if root is null, then return

  • solve(left of root, nodes)

  • add value of root into the nodes array

  • solve(right of root, nodes)

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def kthSmallest(self, root, k):
      """
      :type root: TreeNode
      :type k: int
      :rtype: int
      """
      nodes = []
      self.solve(root,nodes)
      return nodes[k-1]
   def solve(self, root,nodes):
      if root == None:
         return
      self.solve(root.left,nodes)
      nodes.append(root.val)
      self.solve(root.right,nodes)

Input

[10,5,15,2,7,13]

Output

7
raja
Published on 05-Feb-2020 10:14:44
Advertisements