您的位置:首页 > 其它

[Leetcode 230, Medium] Kth Smallest Element in a BST

2015-07-18 00:26 435 查看
Problem:

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.

Analysis:

Solutions:

C++:

int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode *> node_stack;
        node_stack.push(root);
        TreeNode *p_cur_node = root->left;
        while(p_cur_node || !node_stack.empty()) {
            if(p_cur_node) {
                node_stack.push(p_cur_node);
                p_cur_node = p_cur_node->left;
                continue;
            }
            
            if(!node_stack.empty()) {
                p_cur_node = node_stack.top();
                --k;
                if(k == 0)
                    return p_cur_node->val;
                node_stack.pop();
                p_cur_node = p_cur_node->right;
            }
        }
        
        return -1;
    }
Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: