[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:
http://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/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.reference:
http://www.geeksforgeeks.org/find-k-th-smallest-element-in-bst-order-statistics-in-bst/
[Leetcode] Binary search/tree-230. Kth Smallest Element in a BST