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:

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

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res;
int count;
public int kthSmallest(TreeNode root, int k) {
res = 0;
count = k;
inOrder(root);
return res;
} private void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
count -= 1;
if (count == 0) {
res = root.val;
return;
}
inOrder(root.right);
}
}

最新文章

  1. Hbase的伪分布式安装
  2. Interview Tests
  3. 使用beanUtils操纵javabean
  4. js获取url传递的参数
  5. 20145317彭垚 《Java程序设计》第五次实验报告
  6. zju 2972 Hurdles of 110m(简单的dp)
  7. ASP.NET Application_Error错误日志写入
  8. bzoj1004:[HNOI2008]Cards
  9. PLSQL编程基础
  10. [置顶] Mysql存储过程入门知识
  11. Deep Q-Network 学习笔记(二)—— Q-Learning与神经网络结合使用(有代码实现)
  12. webpack1 新手入门教程
  13. ArcGIS 网络分析[8] ArcObjects二次开发之底层网络分析开发
  14. 用MATLAB结合四种方法搜寻罗马尼亚度假问题
  15. [Swift]LeetCode189. 旋转数组 | Rotate Array
  16. IntelliJ IDEA自动导入包去除星号(import xxx.*)
  17. CSS的块级元素和内联元素的概念
  18. PyCharm 中使用 Pylint 控制代码质量
  19. Python复习笔记(一)高级变量类型
  20. 互评Final版本——可以低头,但没必要——取件帮

热门文章

  1. Python笔记_第一篇_面向过程_第一部分_3.进制、位运算、编码
  2. catalina.out日志膨胀问题解决实例,日志门面commons-logging的实践
  3. PAT Basic 1034 有理数四则运算(20) [数学问题-分数的四则运算]
  4. Chladni Figure CodeForces - 1162D (暴力,真香啊~)
  5. ios ktvhttpcache 音视频缓存插件使用
  6. 数据库T-SQL语言操作(T-SQL语句、数据库、表、视图、索引)
  7. 使用mha 构建mysql高可用碰到几个问题
  8. Spring Boot原理
  9. Codeforces Round #600 (Div. 2)E F
  10. Escape from the Hell