Monday, August 31, 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.
class Solution {
public:
    void pushLefts(stack<TreeNode*>& s, TreeNode* root)
    {
        while(root != NULL)
        {
            s.push(root);
            root = root->left;
        }
    }
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode*> tmp;
        pushLefts(tmp, root);
        while (!tmp.empty())
        {
            TreeNode* cur = tmp.top();
            tmp.pop();
            if (k == 1)
            {
                return cur->val;
            }
            pushLefts(tmp, cur->right);
            k--;
        }
        return -1;
    }
};

No comments:

Post a Comment