关闭

230. Kth Smallest Element in a BST

标签: Kth Smallest ElementleetcodeBST
154人阅读 评论(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?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

这又是一道关于二叉搜索树 Binary Search Tree 的题, LeetCode中关于BST的题有Validate Binary Search Tree 验证二叉搜索树, Recover Binary Search Tree 复原二叉搜索树, Binary Search Tree Iterator 二叉搜索树迭代器, Unique Binary Search Trees 独一无二的二叉搜索树, Unique Binary Search Trees II 独一无二的二叉搜索树之二Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树 和 Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树。那么这道题给的提示是让我们用BST的性质来解题,最重要的性质是就是左<根<右,那么如果用中序遍历所有的节点就会得到一个有序数组。所以解题的关键还是中序遍历啊。关于二叉树的中序遍历可以参见我之前的博客Binary Tree Inorder Traversal 二叉树的中序遍历,里面有很多种方法可以用,我们先来看一种非递归的方法:

解法一

复制代码
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        int cnt = 0;
        stack<TreeNode*> s;
        TreeNode *p = root;
        while (p || !s.empty()) {
            while (p) {
                s.push(p);
                p = p->left;
            }
            p = s.top(); s.pop();
            ++cnt;
            if (cnt == k) return p->val;
            p = p->right;
        }
        return 0;
    }
};
复制代码

 

当然,此题我们也可以用递归来解,还是利用中序遍历来解,代码如下:

解法二:

复制代码
class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        return kthSmallestDFS(root, k);
    }
    int kthSmallestDFS(TreeNode* root, int &k) {
        if (!root) return -1;
        int val = kthSmallestDFS(root->left, k);
        if (!k) return val;
        if (!--k) return root->val;
        return kthSmallestDFS(root->right, k);
    }
};
复制代码

 

参考资料:

https://leetcode.com/discuss/43275/use-divide-and-conquer-to-solve-this-problem

 

LeetCode All in One 题目讲解汇总(持续更新中...)

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:62992次
    • 积分:2119
    • 等级:
    • 排名:第19819名
    • 原创:148篇
    • 转载:71篇
    • 译文:0篇
    • 评论:3条
    最新评论