Leetcode[230] Kth Smallest Element in a BST
29 Nov 2015###Task1 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?
Hint:
Try to utilize the property of a BST.
What if you could modify the BST node's structure?
The optimal runtime complexity is O(height of BST).
###Python ####O(K)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
stack = []
prev = root
count = 0
while len(stack) or prev:
while prev:
stack.append(prev)
prev = prev.left
cur = stack.pop()
count += 1
if count == k:
return cur.val
prev = cur.right
###Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void inorder(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return ;
}
inorder(root.left, list);
list.add(root.val);
inorder(root.right, list);
return;
}
public int kthSmallest(TreeNode root, int k) {
if (root == null) {
return 0;
}
ArrayList<Integer> list = new ArrayList<Integer>();
inorder(root, list);
return list.get(k - 1);
}
}
###Points
如果BST节点TreeNode的属性可以扩展,则再添加一个属性leftCnt,记录左子树的节点个数
记当前节点为node
当node不为空时循环:
若k == node.leftCnt + 1:则返回node
否则,若k > node.leftCnt:则令k -= node.leftCnt + 1,令node = node.right
否则,node = node.left
上述算法时间复杂度为O(BST的高度)