leetcode -- Kth Smallest Element in a BST -- 简单重点

https://leetcode.com/problems/kth-smallest-element-in-a-bst/

这里注意 BST的left subtree 所有**node都要小于root, right subtree 所有node都要大于**root。没有等于,并且是所有node

思路1 非递归用stack

用inorder的模板就行

class Solution(object):
    def inorder(self, root, res, k):
        stack = []

        while stack or root:
            if root:
                stack.append(root)
                root = root.left
            else:
                root = stack.pop()
                res.append(root)
                if len(res) == k:
                    return root.val
                root = root.right
    def kthSmallest(self, root, k):
        """ :type root: TreeNode :type k: int :rtype: int """
        return self.inorder(root, [], k)

思路2 递归

计算一个树的node个数,
参考http://www.rainatian.com/2015/07/06/leetcode-python-java-kth-smallest-element-in-a-bst/

class Solution(object):

    def SizeOfTree(self, root):
        if root is None:
            return 0
        return self.SizeOfTree(root.left) + self.SizeOfTree(root.right) + 1

    def kthSmallest(self, root, k):
        if root is None:
            return 0

        leftsize = self.SizeOfTree(root.left)
        if leftsize == k-1:
            return root.val
        elif leftsize > k-1:
            return self.kthSmallest(root.left,k)
        else:
            return self.kthSmallest(root.right,(k-1-leftsize))     

这个效率还没有非递归高,

思路3 O(BST的高度)

第二遍的时候再看

参考
http://bookshadow.com/weblog/2015/07/02/leetcode-kth-smallest-element-bst/

你可能感兴趣的:(LeetCode)