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?

/**
 * 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;
        int leftNodeSum = nodeSum(root.left);
        if (k == leftNodeSum + 1) return root.val;
        else if (k < leftNodeSum + 1) return kthSmallest(root.left, k);
        else return kthSmallest(root.right, k - leftNodeSum - 1);
    }
    private int nodeSum(TreeNode root) {
        if (root == null) return 0;
        return nodeSum(root.left) + nodeSum(root.right) + 1;
    }
    */
    public int kthSmallest(TreeNode root, int k) {
        int count = 0;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                TreeNode node = stack.pop();
                count++;
                if (count == k) return node.val;
                cur = node.right;
            }
        }
        return 0;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s