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

Posted 安新

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Binary search/tree-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.

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?

 

Solution:

 

1.  #1st naive idea is to use inorder traversal, because of the characteristics of binary search tree, when the kth number is visited,
#it is the kth smallest value time complexity o(k), worst time complexity o(n)

  

  (1). use recursive way

 1  def bfsInorderRecursive(node, ansLst):
 2             if node:
 3                 bfsInorderRecursive(node.left, ansLst)
 4                 #print ("d: ", k, node.val)
 5                 ansLst.append(node.val)
 6                 bfsInorderRecursive(node.right, ansLst)
 7         
 8         ansLst = []
 9         bfsInorderRecursive(root, ansLst)
10         return ansLst[k-1]

 (2) use iterative way: use stack to add all left node into a stack, then   iterate to pop out to check the node‘s right node existing or not to insert into stack

 1       current = root
 2         stk = []            #stack
 3         cnt = 1
 4         done = 0
 5         while (not done):
 6             if current is not None:       #Reach the left most Node of the current Node
 7                 stk.append(current)
 8                 current = current.left
 9             else:
10                 if (len(stk) > 0):
11                     current = stk.pop(-1)
12                     if cnt == k:
13                        return current.val
14                     cnt += 1
15                     current = current.right
16                 else: done = 1
17         return 0
18         

reference:

 

follow up problem:

add another count property  for current node,  left subtree‘s node number as current node‘s count
we can keep track of count in a subtree of any node while building the tree.



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

LeetCode 704. Binary Search

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

[Leetcode] Recover Binary Search Tree

[LeetCode] 173. Binary Search Tree Iterator_Medium_tag: Binary Search Tree

LeetCode98. Validate Binary Search Tree

Validate Binary Search Tree -- LeetCode