码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 230 Kth Smallest Element in a BST

时间:2015-07-02 09:53:05      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

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?

最先想到的思路就是中序遍历后找到结果数组中的第k-1项,为了节约时间可以每次都判断结果数组长度,达到k即返回最后一项。

def kth_smallest(root, k)
    stack,ans = [[false,root]], []
    while not stack.empty?
        visit, node = stack.pop
        if node
            if visit
               ans << node.val
               return ans[-1] if ans.length == k
            else
                stack << [false,node.right] << [true,node] << [false,node.left]
            end
        end
    end
end

 

Try the left subtree first. If that made k zero, then its answer is the overall answer and we return it right away. Otherwise, decrease k for the current node, and if that made k zero, then we return the current node‘s value right away. Otherwise try the right subtree and return whatever comes back from there.

int kthSmallest(TreeNode* root, int k) {
    return find(root, k);
}
int find(TreeNode* root, int& k) {
    if (root) {
        int x = find(root->left, k);
        return !k ? x : !--k ? root->val : find(root->right, k);
    }
}

 

Leetcode 230 Kth Smallest Element in a BST

标签:

原文地址:http://www.cnblogs.com/lilixu/p/4615079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!