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?

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).

    分析

最简单的办法,中序遍历,即可以得到递增序列,从而可以找到第k大的元素。时间复杂度O(k)

如果能够修改节点的数据结构TreeNode,可以增加一个字段leftCnt,表示左子树的节点个数。设当前节点为root

  • 若 k == root.leftCnt+1, 则返回root
  • 若 k > node.leftCnt, 则 k -= root.leftCnt+1, root=root.right
  • 否则,node = node.left
    算法复杂度为O(height of BST)

解法1

  1. // Kth Smallest Element in a BST
  2. // Time Complexity: O(k), Space Complexity: O(h)
  3. public class Solution {
  4. public int kthSmallest(TreeNode root, int k) {
  5. Stack s = new Stack<>();
  6. TreeNode p = root;
  7. while (!s.empty() || p != null) {
  8. if (p != null) {
  9. s.push(p);
  10. p = p.left;
  11. } else {
  12. p = s.pop();
  13. --k;
  14. if (k == 0) {
  15. return p.val;
  16. }
  17. p = p.right;
  18. }
  19. }
  20. return -1;
  21. }
  22. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/binary-tree/bst/kth-smallest-element-in-a-bst.html