Tuesday, October 13, 2015

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:
  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).
Solution1: iteratively inorder traversal, run time complexity is O(n), space complexity is O(logn).
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        
        Stack stack = new Stack();
        int res = 0;
        
        while (!stack.isEmpty() || root != null) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                TreeNode temp = stack.pop();
                k--;
                if (k == 0) {
                    res = temp.val;
                }
                root = temp.right;
            }
        }
        
        return res;
    }
}
Solution2: recursive
Count the number of nodes of left subtree and right subtree recursively. 
If the kth smallest element is in the right subtree, update k as k - (leftCount + 1) (leftCount + 1 = number of left subtree+root node). When k = leftCount + 1, we find the kth smallest element.
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public static int ans = 0;
    public int kthSmallest(TreeNode root, int k) {
        helper(root, k);
        return ans;
    }
    
    public int helper(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        
        int leftCount = helper(root.left, k);
        int rightCount = helper(root.right, k - leftCount - 1);
        if (k == leftCount + 1) {
            ans = root.val;
        }
        
        return leftCount + 1 + rightCount;
    }
}
Reference: https://leetcode.com/discuss/54316/simple-and-clean-java-solution-with-explanation
Follow up: 
Modify the structure of TreeNode, add int leftCount (number of nodes in left subtree of this node)
Assume current TreeNode is node,

while (node != null) {

    if (k == node.leftCount + 1), return node.val;

    if (k > node.leftCount) {

        k -= node.leftCount + 1;

        node = node.right;

    } else {

        node = node.left;

    }

}
Reference: http://bookshadow.com/weblog/2015/07/02/leetcode-kth-smallest-element-bst/ 

No comments:

Post a Comment