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?

题目含义:给出二叉搜索树中第k小的数字

复制代码
 1     private int leftTreeNodeCount(TreeNode root) {
 2         if (root == null) return 0;
 3         return 1 + leftTreeNodeCount(root.left) + leftTreeNodeCount(root.right);
 4     }
 5     
 6     public int kthSmallest(TreeNode root, int k) {
 7 //        在二叉搜索树种,找到第K个小的元素。
 8 //        算法如下:
 9 //        1、计算左子树元素个数left。
10 //        2、 left+1 = K,则根节点即为第K个元素
11 //        3、left >=k, 则第K个元素在左子树中,
12 //        4、left +1 <k, 则转换为在右子树中,寻找第K-left-1元素
13         int leftCount = leftTreeNodeCount(root.left);
14         if (leftCount >= k) {
15             return kthSmallest(root.left, k);
16         } 
17         if (leftCount + 1 < k) return kthSmallest(root.right, k - leftCount - 1);
18         return root.val;        
19     }
复制代码

 

posted @   daniel456  阅读(105)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示