230. 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.

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 题目讲解汇总(持续更新中...)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值