码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 230. Kth Smallest Element in a BST

时间:2019-07-29 20:15:18      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:有序   onclick   elf   pre   event   HERE   amp   play   root   

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

标签:有序   onclick   elf   pre   event   HERE   amp   play   root   

原文地址:https://www.cnblogs.com/pegasus923/p/11266173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!