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

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

时间:2017-06-12 00:42:23      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:bin   recursion   insert   nod   org   exit   note   sum   problem   

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

标签:bin   recursion   insert   nod   org   exit   note   sum   problem   

原文地址:http://www.cnblogs.com/anxin6699/p/6986873.html

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