Leetcode: Kth Smallest Element in a BST

Question

Given a binary search tree, write a function kthSmallest to find the kth 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?

Show Hint
Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Show Tags
Show Similar Problems

Analysis

Solution

# 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):
    def kthSmallest(self, root, k):
        """ :type root: TreeNode :type k: int :rtype: int """

        self.res, self.counter = 0,0

        self.helper(root, k)
        return self.res

    def helper(self, root, k):
        if root.left!=None:
            self.helper(root.left, k)     # record how many nodes in the left subtree

        self.counter += 1    # count +1 because of the root

        if self.counter==k:
            self.res = root.val
            return

        if root.right!=None:
            self.helper(root.right, k)

Take Home Message

  1. use global variable to cut down the number of parameters of function
  2. This problem inspired us how to count the number of recursive function it has finished recursively.

你可能感兴趣的:(Leetcode: Kth Smallest Element in a BST)