当前位置: 首页 > news >正文

LeetCode -- Kth Smallest Element in a BST

Kth Smallest Element in a BST


在BST中查找第k小的数。


思路: 中序遍历+队列


实现代码:





/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int KthSmallest(TreeNode root, int k) 
 {
 	if(k < 1){
		return -1;
	}
 	var q = new Queue<int>();
    Inorder(root, q);
	
	int last = -1;
	for(var i = 0;i < k - 1; i++){
		if(q.Count > 0){
			last = q.Dequeue();
		}
	}
	
	return q.Count > 0 ? q.Dequeue() : last;
 }
 private void Inorder(TreeNode node, Queue<int> queue){
	if(node.left != null){
		Inorder(node.left, queue);
	}
	queue.Enqueue(node.val);
	if(node.right != null){
		Inorder(node.right, queue);
	}
	
 }
}


相关文章:

  • SQL2005CLR函数扩展-环比计算
  • LeetCode -- Majority Element
  • LeetCode -- Max Points on a Line
  • ArcGIS Server Java ADF 案例教程 17
  • LeetCode -- Maximal Square
  • ArcGIS Server Java ADF 案例教程 18
  • LeetCode -- Summary Ranges
  • ArcGIS Server Java ADF 案例教程 19
  • ArcGIS Server Java ADF 案例教程 20
  • LeetCode -- Unique Paths
  • 警惕手机流氓软件的流行
  • LeetCode -- Combination Sum II
  • 学习百度、腾讯如何把产品做到极致(转载)
  • LeetCode -- Edit Distance
  • Leetcode -- Find Minimum in Rotated Sorted Array
  • 230. Kth Smallest Element in a BST
  • Essential Studio for ASP.NET Web Forms 2017 v2,新增自定义树形网格工具栏
  • Java 23种设计模式 之单例模式 7种实现方式
  • Unix命令
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 设计模式 开闭原则
  • 深入 Nginx 之配置篇
  • 优秀架构师必须掌握的架构思维
  • AI算硅基生命吗,为什么?
  • NLPIR智能语义技术让大数据挖掘更简单
  • Prometheus VS InfluxDB
  • Semaphore
  • ​LeetCode解法汇总2670. 找出不同元素数目差数组
  • #QT(TCP网络编程-服务端)
  • #常见电池型号介绍 常见电池尺寸是多少【详解】
  • (30)数组元素和与数字和的绝对差
  • (4)事件处理——(7)简单事件(Simple events)
  • (6)STL算法之转换
  • (带教程)商业版SEO关键词按天计费系统:关键词排名优化、代理服务、手机自适应及搭建教程
  • (顶刊)一个基于分类代理模型的超多目标优化算法
  • (六)库存超卖案例实战——使用mysql分布式锁解决“超卖”问题
  • (论文阅读26/100)Weakly-supervised learning with convolutional neural networks
  • (深入.Net平台的软件系统分层开发).第一章.上机练习.20170424
  • (转)C#调用WebService 基础
  • .NET Standard / dotnet-core / net472 —— .NET 究竟应该如何大小写?
  • .NET(C#、VB)APP开发——Smobiler平台控件介绍:Bluetooth组件
  • .NET/C# 反射的的性能数据,以及高性能开发建议(反射获取 Attribute 和反射调用方法)
  • /usr/local/nginx/logs/nginx.pid failed (2: No such file or directory)
  • @param注解什么意思_9000字,通俗易懂的讲解下Java注解
  • @property括号内属性讲解
  • [ 云计算 | AWS 实践 ] Java 如何重命名 Amazon S3 中的文件和文件夹
  • [ 转载 ] SharePoint 资料
  • [Android] Implementation vs API dependency
  • [BZOJ 2142]礼物(扩展Lucas定理)
  • [codeforces]Checkpoints
  • [CSS] - 修正IE6不支持position:fixed的bug
  • [Geek Challenge 2023] web题解
  • [hdu 1247]Hat’s Words [Trie 图]
  • [HTTP]HTTP协议的状态码
  • [Java][Android][Process] ProcessBuilder与Runtime差别