Leetcode 230. Kth Smallest Element in a BST

Posted pegasus923

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 230. Kth Smallest Element in a BST相关的知识,希望对你有一定的参考价值。

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?


  • 因为是binary search tree,所以是有序的,变成DFS / BST遍历树。
  • DFS
    • Time complexity : O(N) to build a traversal.
    • Space complexity : O(N) to keep an inorder traversal.
  • BFS
    • Time complexity : O(H+k), where HH is a tree height. This complexity is defined by the stack, which contains at least H + kH+k elements, since before starting to pop out one has to go down to a leaf. This results in O(logN+k) for the balanced tree and O(N+k) for completely unbalanced tree with all the nodes in the left subtree.
    • Space complexity : O(H+k), the same as for time complexity, O(N+k) in the worst case, and O(logN+k) in the average case.
技术图片
 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:
 9     def kthSmallest1(self, root: TreeNode, k: int) -> int:
10         def inorder(r):
11             return inorder(r.left) + [r.val] + inorder(r.right) if r else [] # pythonic style
12         
13         return inorder(root)[k - 1]     
14     
15     def kthSmallest(self, root: TreeNode, k: int) -> int:
16         stack = []
17         
18         while True:
19             while root:
20                 stack.append(root)
21                 root = root.left
22             
23             root = stack.pop()
24             k -= 1
25             
26             if not k:
27                 return root.val
28             
29             root = root.right
View Python Code

 

以上是关于Leetcode 230. Kth Smallest Element in a BST的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 230. Kth Smallest Element in a BST

Leetcode 230. Kth Smallest Element in a BST

Leetcode 230: Kth Smallest Element in a BST

leetcode 230. Kth Smallest Element in a BST

[Leetcode] Binary search/tree-230. Kth Smallest Element in a BST

[LeetCode] 230. Kth Smallest Element in a BST