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?

Show Hint

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

解法一:递归中序遍历,必须全部遍历

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int kthSmallest(TreeNode* root, int k) {
  13. vector<int> ret;
  14. inOrder(root, ret);
  15. return ret[k-];
  16. }
  17. void inOrder(TreeNode* root, vector<int>& ret)
  18. {
  19. if(root)
  20. {
  21. inOrder(root->left, ret);
  22. ret.push_back(root->val);
  23. inOrder(root->right, ret);
  24. }
  25. }
  26. };

解法二:迭代中序遍历,遍历到第k个元素停止

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int kthSmallest(TreeNode* root, int k) {
  13. vector<int> ret;
  14. stack<TreeNode*> stk;
  15. stk.push(root);
  16. TreeNode* cur = root;
  17. while(cur->left)
  18. {
  19. stk.push(cur->left);
  20. cur = cur->left;
  21. }
  22. while(!stk.empty())
  23. {
  24. TreeNode* top = stk.top();
  25. stk.pop();
  26. ret.push_back(top->val);
  27. if(ret.size() == k)
  28. break;
  29. if(top->right)
  30. {
  31. TreeNode* cur = top->right;
  32. stk.push(cur);
  33. while(cur->left)
  34. {
  35. stk.push(cur->left);
  36. cur = cur->left;
  37. }
  38. }
  39. }
  40. return ret[k-];
  41. }
  42. };

【LeetCode】230. Kth Smallest Element in a BST (2 solutions)的更多相关文章

  1. 【LeetCode】230. Kth Smallest Element in a BST

    Difficulty: Medium  More:[目录]LeetCode Java实现 Description https://leetcode.com/problems/kth-smallest- ...

  2. 【刷题-LeetCode】230. Kth Smallest Element in a BST

    Kth Smallest Element in a BST Given a binary search tree, write a function kthSmallest to find the k ...

  3. 【LeetCode】378. Kth Smallest Element in a Sorted Matrix 解题报告(Python)

    [LeetCode]378. Kth Smallest Element in a Sorted Matrix 解题报告(Python) 标签: LeetCode 题目地址:https://leetco ...

  4. 【Leetcode】378. Kth Smallest Element in a Sorted Matrix

    Question: Given a n x n matrix where each of the rows and columns are sorted in ascending order, fin ...

  5. 【leetcode】378. Kth Smallest Element in a Sorted Matrix(TOP k 问题)

    Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kt ...

  6. LeetCode OJ 230. Kth Smallest Element in a BST

    Total Accepted: 46445 Total Submissions: 122594 Difficulty: Medium Given a binary search tree, write ...

  7. 【LeetCode】215. Kth Largest Element in an Array (2 solutions)

    Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is t ...

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

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

  9. [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 ...

随机推荐

  1. Android -- Drag&&Drop

    Android3.0提供了drag/drop框架,利用此框架可以实现使用拖放手势将一个view拖放到当前布局中的另外一个view中. 实现拖放的步骤 首先,我们先了解一下拖放过程,从官方文档可以知道, ...

  2. 开源项目kcws代码分析--基于深度学习的分词技术

    http://blog.csdn.net/pirage/article/details/53424544 分词原理 本小节内容参考待字闺中的两篇博文: 97.5%准确率的深度学习中文分词(字嵌入+Bi ...

  3. 前端笔记----jquery入门知识点总结 (转)

    http://www.cnblogs.com/cwp-bg/p/7633623.html 一.jquery的加载方法 $(document).ready(function(){js代码}); $(fu ...

  4. js 前加分号和感叹号的含义

    ;!function(){}();  ;!有什么用? 从语法上来开.Javascript中分号表示语句结束,在开头加上.可能是为了压缩的时候和别的方法切割一下,表示一个新的语句開始.所以,假设在一个单 ...

  5. Android:安装时提示:INSTALL_FAILED_INSUFFICIENT_STORAGE

    在将程序发布到手机上时提示该错误: INSTALL_FAILED_INSUFFICIENT_STORAGE 解决方法: 1. adb shell 2. #df # df df Filesystem   ...

  6. Android中创建PopupMenu弹出式菜单

    之前写过一篇创建option menu的文章:Android中创建option menu 本文主要是讲如何创建PopupMenu弹出式菜单 1.首先创建menu文件menu2.xml: <?xm ...

  7. hive中简单介绍分区表(partition table)——动态分区(dynamic partition)、静态分区(static partition)

    一.基本概念 hive中分区表分为:范围分区.列表分区.hash分区.混合分区等. 分区列:分区列不是表中的一个实际的字段,而是一个或者多个伪列.翻译一下是:“在表的数据文件中实际上并不保存分区列的信 ...

  8. Spark的运行模式(1)--Local和Standalone

    Spark一共有5种运行模式:Local,Standalone,Yarn-Cluster,Yarn-Client和Mesos. 1. Local Local模式即单机模式,如果在命令语句中不加任何配置 ...

  9. ES6 class 技术点拾遗

    语法 方法不需要加function,方法之间不需要加分号 class Point { constructor(x, y) { this.x = x; this.y = y; } toString() ...

  10. Java继承Exception自定义异常类教程以及Javaweb中用Filter拦截并处理异常

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6403033.html 在项目中的应用见: https://github.com/ygj0930/CoupleS ...