LeetCode230 Kth smallest Element in a BST

method1, which is pretty simple, in order tranverse
method2, which uses binary search, we count the number of nodes contains in the left subtree of current node, if this number is larger than k-1, then this kth smallest element must contains in this left subtree, recursion all the way down. and if the number is less than k-1, then k must exist in right subtree, so we recursion to right tree. and if the number is equals to k-1, then we already find the node we are looking for.

the code in Python:

class Solution(object):
    def kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        def getsize(node):
            if not node:
                return 0
            return 1 + getsize(node.left) + getsize(node.right)
        if not root:
            return 0
        left_size = getsize(root.left)
        if k == left_size + 1:
            return root.val
        elif left_size >= k:
            return self.kthSmallest(root.left, k)
        else:
            return self.kthSmallest(root.right, k-left_size-1)
posted @ 2020-05-31 06:46  EvanMeetTheWorld  阅读(14)  评论(0)    收藏  举报