230. Kth Smallest Element in a BST

来源:互联网 发布:178软件源地址 编辑:程序博客网 时间:2024/05/22 01:39

My solution with a global variable

class Solution(object):    def kthSmallest(self, root, k):        """        :type root: TreeNode        :type k: int        :rtype: int        """        self.result = 0        _ = self._tree_count(root, k)        return self.result    def _tree_count(self, root, k):        if not root:            return 0        left = self._tree_count(root.left, k)        if left + 1 == k:            self.result = root.val        right = self._tree_count(root.right, k - left - 1)        return left + right + 1
原创粉丝点击