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?

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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        int numOfLeft = countNodes(root->left);

        if(k <= numOfLeft){
            return kthSmallest(root->left, k);
        }else if( k > numOfLeft + 1){
            return kthSmallest(root->right, k - 1- numOfLeft);
        }else
            return root->val;
    }
private:
    int countNodes(TreeNode *r){
        if(r == NULL)   return 0;

        return countNodes(r->left) + 1 + countNodes(r->right);
    }
};

inorder-traversal

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode *> st;

        while(!st.empty() || root != NULL){
            if(root){
                st.push(root);
                root = root->left;
            }else{
                auto temp = st.top();
                st.pop();
                if( --k == 0)    return temp->val;

                root = temp->right;
            }
        }
        //can't go here, because k is alway valid
        return -1;
    }
};

results matching ""

    No results matching ""