prepbook
  • Introduction
  • Some common stuff
    • python __repr__
    • HackerRank input tips
  • Data Structures and Algorithms
    • Breadth first search
    • Depth First Search
    • Dijkstra
    • A* Search Algorithm
    • Binary Search
    • python counter
    • Sorting
      • Merge Sort
      • Quick Sort
    • Priority Queue
  • Multiprocessing vs Threading
  • Common Coding
    • Find loop in lin list
    • Maximum sum subarray
  • Coding
    • Valid palindrome
    • Palindrome number
    • Remove duplicates from sorted array
    • Island perimeter
    • Serialize and Deserialize Binary Tree
    • Valid Soduku
    • Word Pattern
    • Word Pattern II
    • Group Anagrams
    • Implement Trie
    • Deep copy list with random node
    • Palindrome Permutation
    • Combination Sum
    • Clone Graph
    • Generate parenthesis
    • Fibonacci Number
    • LRU Cache
    • Merge two sorted arrays in place
    • Hamming Distance
    • Merge K sorted arrays
    • Kth smalles element in BST
    • Kth largest element in an array
    • Remove duplicates from sorted list
    • Power of 2
    • Nested list weight sum
    • SIngle number in a list
    • Factor combinations
    • Delete node from BST
  • hacker Rank
    • Coding
      • print staircase
      • Drawing book
      • Challenge 0
      • Min-Max sum
  • WorkRelatedCoding
    • Rectangle Overlap
  • Python tips
Powered by GitBook
On this page

Was this helpful?

  1. Coding

Kth smalles element in BST

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:

  1. Try to utilize the property of a BST.

  2. What if you could modify the BST node's structure?

  3. 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)
PreviousMerge K sorted arraysNextKth largest element in an array

Last updated 5 years ago

Was this helpful?