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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!