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.
 * 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 num = 0;
        int result = 0;
        visit(root, k, num, result);

        return result;
    }
    
private:
    void visit(TreeNode *root, int k, int &num, int &result)
    {
        if (root == NULL)
        {
            return;
        }

        visit(root->left, k, num, result);
        if (num < k)
        {
            num += 1;
            if (num == k)
            {
                result = root->val;
                return;
            }
        }
        visit(root->right, k, num, result);
    }
};


你可能感兴趣的:(Kth Smallest Element in a BST)