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.

Example 1:

  1. Input: root = [3,1,4,null,2], k = 1
  2. 3
  3. / \
  4. 1 4
  5. \
  6.   2
  7. Output: 1

Example 2:

  1. Input: root = [5,3,6,2,4,null,null,1], k = 3
  2. 5
  3. / \
  4. 3 6
  5. / \
  6. 2 4
  7. /
  8. 1
  9. Output: 3

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?

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

这又是一道关于二叉搜索树 Binary Search Tree 的题, LeetCode 中关于 BST 的题有 Validate Binary Search TreeRecover Binary Search TreeBinary Search Tree IteratorUnique Binary Search TreesUnique Binary Search Trees IIConvert Sorted Array to Binary Search Tree 和 Convert Sorted List to Binary Search Tree。那么这道题给的提示是让我们用 BST 的性质来解题,最重要的性质是就是左<根<右,如果用中序遍历所有的节点就会得到一个有序数组。所以解题的关键还是中序遍历啊。关于二叉树的中序遍历可以参见我之前的博客 Binary Tree Inorder Traversal,里面有很多种方法可以用,先来看一种非递归的方法,中序遍历最先遍历到的是最小的结点,只要用一个计数器,每遍历一个结点,计数器自增1,当计数器到达k时,返回当前结点值即可,参见代码如下:

解法一:

  1. class Solution {
  2. public:
  3. int kthSmallest(TreeNode* root, int k) {
  4. int cnt = ;
  5. stack<TreeNode*> s;
  6. TreeNode *p = root;
  7. while (p || !s.empty()) {
  8. while (p) {
  9. s.push(p);
  10. p = p->left;
  11. }
  12. p = s.top(); s.pop();
  13. ++cnt;
  14. if (cnt == k) return p->val;
  15. p = p->right;
  16. }
  17. return ;
  18. }
  19. };

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

解法二:

  1. class Solution {
  2. public:
  3. int kthSmallest(TreeNode* root, int k) {
  4. return kthSmallestDFS(root, k);
  5. }
  6. int kthSmallestDFS(TreeNode* root, int &k) {
  7. if (!root) return -;
  8. int val = kthSmallestDFS(root->left, k);
  9. if (k == ) return val;
  10. if (--k == ) return root->val;
  11. return kthSmallestDFS(root->right, k);
  12. }
  13. };

再来看一种分治法的思路,由于 BST 的性质,可以快速定位出第k小的元素是在左子树还是右子树,首先计算出左子树的结点个数总和 cnt,如果k小于等于左子树结点总和 cnt,说明第k小的元素在左子树中,直接对左子结点调用递归即可。如果k大于 cnt+1,说明目标值在右子树中,对右子结点调用递归函数,注意此时的k应为 k-cnt-1,应为已经减少了 cnt+1 个结点。如果k正好等于 cnt+1,说明当前结点即为所求,返回当前结点值即可,参见代码如下:

解法三:

  1. class Solution {
  2. public:
  3. int kthSmallest(TreeNode* root, int k) {
  4. int cnt = count(root->left);
  5. if (k <= cnt) {
  6. return kthSmallest(root->left, k);
  7. } else if (k > cnt + ) {
  8. return kthSmallest(root->right, k - cnt - );
  9. }
  10. return root->val;
  11. }
  12. int count(TreeNode* node) {
  13. if (!node) return ;
  14. return + count(node->left) + count(node->right);
  15. }
  16. };

这道题的 Follow up 中说假设该 BST 被修改的很频繁,而且查找第k小元素的操作也很频繁,问我们如何优化。其实最好的方法还是像上面的解法那样利用分治法来快速定位目标所在的位置,但是每个递归都遍历左子树所有结点来计算个数的操作并不高效,所以应该修改原树结点的结构,使其保存包括当前结点和其左右子树所有结点的个数,这样就可以快速得到任何左子树结点总数来快速定位目标值了。定义了新结点结构体,然后就要生成新树,还是用递归的方法生成新树,注意生成的结点的 count 值要累加其左右子结点的 count 值。然后在求第k小元素的函数中,先生成新的树,然后调用递归函数。在递归函数中,不能直接访问左子结点的 count 值,因为左子节结点不一定存在,所以要先判断,如果左子结点存在的话,那么跟上面解法的操作相同。如果不存在的话,当此时k为1的时候,直接返回当前结点值,否则就对右子结点调用递归函数,k自减1,参见代码如下:

解法四:

  1. // Follow up
  2. class Solution {
  3. public:
  4. struct MyTreeNode {
  5. int val;
  6. int count;
  7. MyTreeNode *left;
  8. MyTreeNode *right;
  9. MyTreeNode(int x) : val(x), count(), left(NULL), right(NULL) {}
  10. };
  11.  
  12. MyTreeNode* build(TreeNode* root) {
  13. if (!root) return NULL;
  14. MyTreeNode *node = new MyTreeNode(root->val);
  15. node->left = build(root->left);
  16. node->right = build(root->right);
  17. if (node->left) node->count += node->left->count;
  18. if (node->right) node->count += node->right->count;
  19. return node;
  20. }
  21.  
  22. int kthSmallest(TreeNode* root, int k) {
  23. MyTreeNode *node = build(root);
  24. return helper(node, k);
  25. }
  26.  
  27. int helper(MyTreeNode* node, int k) {
  28. if (node->left) {
  29. int cnt = node->left->count;
  30. if (k <= cnt) {
  31. return helper(node->left, k);
  32. } else if (k > cnt + ) {
  33. return helper(node->right, k - - cnt);
  34. }
  35. return node->val;
  36. } else {
  37. if (k == ) return node->val;
  38. return helper(node->right, k - );
  39. }
  40. }
  41. };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/230

类似题目:

Binary Tree Inorder Traversal

Second Minimum Node In a Binary Tree

参考资料:

https://leetcode.com/problems/kth-smallest-element-in-a-bst/

https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63659/what-if-you-could-modify-the-bst-nodes-structure

https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63660/3-ways-implemented-in-JAVA-(Python)%3A-Binary-Search-in-order-iterative-and-recursive

https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/63743/Java-divide-and-conquer-solution-considering-augmenting-tree-structure-for-the-follow-up

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

[LeetCode] Kth Smallest Element in a BST 二叉搜索树中的第K小的元素的更多相关文章

  1. [LeetCode] 230. Kth Smallest Element in a BST 二叉搜索树中的第K小的元素

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  2. LeetCode 230 Kth Smallest Element in a BST 二叉搜索树中的第K个元素

    1.非递归解法 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * ...

  3. 230 Kth Smallest Element in a BST 二叉搜索树中第K小的元素

    给定一个二叉搜索树,编写一个函数kthSmallest来查找其中第k个最小的元素. 注意:你可以假设k总是有效的,1≤ k ≤二叉搜索树元素个数. 进阶:如果经常修改二叉搜索树(插入/删除操作)并且你 ...

  4. [leetcode] 230. Kth Smallest Element in a BST 找出二叉搜索树中的第k小的元素

    题目大意 https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ 230. Kth Smallest Elem ...

  5. Leetcode Kth Smallest Element in a BST

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  6. [LeetCode] Insert into a Binary Search Tree 二叉搜索树中插入结点

    Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert t ...

  7. LeetCode Kth Smallest Element in a BST(数据结构)

    题意: 寻找一棵BST中的第k小的数. 思路: 递归比较方便. /** * Definition for a binary tree node. * struct TreeNode { * int v ...

  8. [LeetCode] Inorder Successor in BST 二叉搜索树中的中序后继节点

    Given a binary search tree and a node in it, find the in-order successor of that node in the BST. No ...

  9. [LeetCode] 285. Inorder Successor in BST 二叉搜索树中的中序后继节点

    Given a binary search tree and a node in it, find the in-order successor of that node in the BST. Th ...

随机推荐

  1. SQL实用

    实用的SQL语句   行列互转 create table test(id int,name varchar(20),quarter int,profile int) insert into test  ...

  2. 微信小程序基础入门

    准备 Demo 项目地址 https://github.com/zce/weapp-demo Clone or Download(需准备GIT环境) $ cd path/to/project/root ...

  3. 「译」JUnit 5 系列:扩展模型(Extension Model)

    原文地址:http://blog.codefx.org/design/architecture/junit-5-extension-model/ 原文日期:11, Apr, 2016 译文首发:Lin ...

  4. 了解java注解

    类似于下面这样的就是注解 注解可以在类上,成员变量上,方法上等 假如有2个注解是这样的:(其中的Author和Date) 那么这2个注解的定义就是这样的: Author注解: Date注解: 可以看到 ...

  5. STL: unordered_map 自定义键值使用

    使用Windows下 RECT 类型做unordered_map 键值 1. Hash 函数 计算自定义类型的hash值. struct hash_RECT { size_t operator()(c ...

  6. Lind.DDD敏捷领域驱动框架~介绍

    回到占占推荐博客索引 最近觉得自己的框架过于复杂,在实现开发使用中有些不爽,自己的朋友们也经常和我说,框架太麻烦了,要引用的类库太多:之前架构之所以这样设计,完全出于对职责分离和代码附复用的考虑,主要 ...

  7. gRPC源码分析2-Server的建立

    gRPC中,Server.Client共享的Class不是很多,所以我们可以单独的分别讲解Server和Client的源码. 通过第一篇,我们知道对于gRPC来说,建立Server是非常简单的,还记得 ...

  8. Java中日期的转化

    4.如何取得年月日.小时分秒? 创建java.util.Calendar实例(Calendar.getInstance()),调用其get()方法传入不同的参数即可获得参数所对应的值,如:calend ...

  9. CentOS7下安装Python的pip

    root用户使用yum install -y python-pip 时会报如下错误: No package python-pip available Error:Nothing to do 解决方法如 ...

  10. Android 底部弹出Dialog(横向满屏)

    项目中经常需要底部弹出框,这里我整理一下其中我用的比较顺手的一个方式(底部弹出一个横向满屏的dialog). 效果图如下所示(只显示关键部分): 步骤如下所示: 1.定义一个dialog的布局(lay ...