Kth Smallest Element in a BST

Problem Id: 230 Difficulty: Medium Tag: Binary Search Tag: Tree


Intuition

Use inorder traversal, and add an attribute to mark the index of the current node.

Solution


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        self.index = 0
        self.k = k
        self.result = None
        self._helper(root)
        return self.result.val

    def _helper(self, node):
        if node is None:
            return
        self._helper(node.left)
        self.index += 1
        if self.index == self.k:
            self.result = node
        self._helper(node.right)