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.

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

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
vector<int> ret;
inOrder(root, ret);
return ret[k-];
}
void inOrder(TreeNode* root, vector<int>& ret)
{
if(root)
{
inOrder(root->left, ret);
ret.push_back(root->val);
inOrder(root->right, ret);
}
}
};

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

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
vector<int> ret;
stack<TreeNode*> stk;
stk.push(root);
TreeNode* cur = root;
while(cur->left)
{
stk.push(cur->left);
cur = cur->left;
}
while(!stk.empty())
{
TreeNode* top = stk.top();
stk.pop();
ret.push_back(top->val);
if(ret.size() == k)
break;
if(top->right)
{
TreeNode* cur = top->right;
stk.push(cur);
while(cur->left)
{
stk.push(cur->left);
cur = cur->left;
}
}
}
return ret[k-];
}
};

【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. iOS - 切换图片/clip subview/iCarousel

    源代码:点击打开链接 这个图片展示的时候,我只想让它在蓝色的view上展示..就需要去设置view的一个属性clip subview..把这个属性打勾...view有个clip subview属性,选 ...

  2. Mac系统下编译支持Android平台的最新X264编码器

    Mac系统下编译支持Android平台的最新X264编码器 原文来自 http://www.mingjianhua.com,转载请注明出处 1.首先去官网下载最新的x264源代码,解压到任意目录 ht ...

  3. struts2 18拦截器详解(九)

    ScopedModelDrivenInterceptor 该拦截器处于defaultStack第八的位置,其主要功能是从指定的作用域内检索相应的model设置到Action中,该类中有三个相关的属性: ...

  4. PHPExcel合并与拆分单元格

      $objPHPExcel; $filepath="c:\temp.xlsx"; try { $objReader = PHPExcel_IOFactory::createRea ...

  5. IIS发布网站遇到 编译器错误消息: CS0016: 未能写入输出文件“c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary 编

    编译错误: 说明:在编译向该请求提供服务所需资源的过程中出现错误.请检查下列特定错误详细信息并适当地修改源代码. 编译器错误消息:CS0016: 未能写入输出文件“c:\Windows\Microso ...

  6. SpringMVC框架使用注解执行定时任务(转)

    首先要配置我们的SpringMVC文件 xmlns 加下面的内容: xmlns:task="http://www.springframework.org/schema/task" ...

  7. Azure Web应用中设置静态虚拟目录的方法(比如部署Django需要用到)

    一.WEB应用中设置虚拟目录 二.在虚拟目录下放一个文件web.config,内容如下: <?xml version="1.0"?> <configuration ...

  8. Azure Paas SQL 修改用户名密码的相关问题

    现总结如下,供您参考: 1)  如何单独修改每个数据库的密码? 在portal中,我们提供了一个最高权限的,可管理服务器下所有数据库的服务器用户 跟密码,但在实际使用中,由于权限过大,会有潜在的安全隐 ...

  9. 通过HttpClient4.5模拟Form表单文件上传

    public static void main(String[] args) { CloseableHttpClient httpclient = HttpClients.createDefault( ...

  10. Spring 基础概念——DI、IOC(一)

    一.IOC 控制反转 package com.qunar.studyspring.bean; import com.qunar.studyspring.dao.PersonDao; import co ...