LintCode-902: Kth Smallest Element in a BST

这题有很多解法。

解法1. 根据BST的中序遍历是非递减序列这个性质。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the given BST
     * @param k: the given k
     * @return: the kth smallest element in BST
     */
    int kthSmallest(TreeNode * root, int k) {
        vector<int> inOrderList;
        inOrderTraversal(root, inOrderList);
        return inOrderList[k-1];
    }
    
    void inOrderTraversal(TreeNode *root, vector<int> &inOrderList) {
        if (!root) 
            return;
        inOrderTraversal(root->left, inOrderList);
        inOrderList.push_back(root->val);
        inOrderTraversal(root->right, inOrderList);
    }
};

上面代码的时间复杂度是O(n), 最好最坏都是。空间复杂度都是O(n)。

解法2:
BST In-order Traversal的非递归版
有个好处就是可以用个counter来计数。
用 stack,从第一个点开始,走 k-1 步,就是第 k 个点了。
时间复杂度是 O(h + k) h 是树的高度。可以理解成一开始先要走到最左边最下面的节点,这里要耗费O(h),然后再从这个节点开始,又需要走O(k)步,所以是O(h+k)。
下次实践。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the given BST
     * @param k: the given k
     * @return: the kth smallest element in BST
     */
    int kthSmallest(TreeNode *root, int k) {
        stack<TreeNode *> stk;
        int count = 0;
        while (root || !stk.empty()) {
            while(root) {
                stk.push(root);
                root = root->left;
            }
            root = stk.top();
            stk.pop();
            count++;
            if (count == k) {
                return root->val;
            }
            root = root->right;
        }
    }
};

解法3:Quick-Select。
详见
https://www.jiuzhang.com/solution/kth-smallest-element-in-a-bst/#tag-highlight
下次实践。

Challenge
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?

答案是用QuickSelect方法做预处理,把每个BST节点的子树的节点个数记录下来,可以在建树的时候一起完成。下次实践一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值