2.3 Kth Smallest Element in a BST

Description

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

Method

1 : inorder traverse non-recursive : stack

Time and Space Complexity

Code

public class Solution {

public int kthSmallest(TreeNode root, int k) {
       if (root == null || k <= 0){
           return 0;
       }
       Stack<TreeNode> s = new Stack<TreeNode>();
       TreeNode cur = root;

       while (cur != null || !s.isEmpty()){
              while (cur != null){
                     s.push(cur);
                     cur = cur.left;
              }
              cur = s.peek();
              s.pop();
              k--;
              if (k == 0){
                  break;
              }
              cur = cur.right;
       }
       return cur.val;

}

}

results matching ""

    No results matching ""