DEV Community

Discussion on: Kth Smallest Element in a BST, solving Netflix Interview question.

ayanb profile image
Ayan Banerjee • Edited on

You can also perform iterative inorder traversal and improve the time complexity to O(H + K). For a balanced tree H = logN however, for a skewed tree, it can be H = N.

def kthSmallest(root, k):
    s = []  # stack
    while root != None or s:
        while root != None:
            root = root.left
        root = s[-1]
        k -= 1
        if k == 0: return root.val
        root = root.right
akhilpokle profile image
Akhil Author

Thanks for sharing :)