代码改变世界

[LeetCode] 230. Kth Smallest Element in a BST_Medium tag: Inorder Traversal

2018-07-24 00:51  Johnson_强生仔仔  阅读(293)  评论(0编辑  收藏  举报

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.

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3

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?

 

这个题目如果不考虑follow up, 就很简单了, 用LeetCode questions conlusion_InOrder, PreOrder, PostOrder traversal里面inOrder traversal的方式, 然后返回ans[k-1]即可.

T: O(n),  S: O(n)  因为stack的Space已经是O(n), 所以是否省掉ans的space意义不大.

至于follow up如果经常被modified的话, 我们可以将LIstNode的structure加入一个parent指向他的parent, 然后有一个kth element指针, 当delete的值大于指针的值, 不变, 如果小于的话,就将kth element向右移, 如果insert的值大于指针的值, 不变, 同理如果小于指针的值, 向左移动.

 

code

1. recursive

class Solution:
    def kthSmall(self, root, k):
        def helper(root):
            if not root: return
            helper(root.left)
            ans.append(root.val)
            helper(root.right)
        ans = []
        helper(root)
        return ans[k-1]

 

2. iterable

class Solution:
    def kthSmall(self, root, k):
        stack = []
        while stack or root:
            if root:
                stack.append(root)
                root = root.left
            else:
                node = stack.pop()
                k-= 1
                if k == 0: return node.val
                root = node.right