leetcode--Kth Smallest Element in a BST
来源:互联网 发布:淘宝网怎样和微信绑定 编辑:程序博客网 时间:2024/06/03 14:48
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?
Hint:
- Try to utilize the property of a BST.
- What if you could modify the BST node's structure?
- The optimal runtime complexity is O(height of BST).
题意:在BST树中,查找第k小的节点值
分类:二叉树
解法1:BST树很多问题我们都可以使用中序遍历来解决,这个也不例外
我们设置一个当前访问的元素个数cur,在中序遍历过程中,每要访问一个节点,cur加1
当cur和k相等时,这就是我们要找的节点,返回即可
利用递归来进行中序遍历,如果左子树找不到,则判断是不是当前节点,不是,则在右子树接着找
如果左子树找到了,直接返回
原文链接http://blog.csdn.net/crazy__chen/article/details/47186417
阅读全文
0 0
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- struts2--使用list属性同时处理多条注册信息
- 一句话证明你学过编程
- HDU_6070_Dirt Ratio_二分_线段树优化
- Android应用内存泄露分析、改善经验总结
- 有关小波的几个术语及常见的小波基介绍
- leetcode--Kth Smallest Element in a BST
- 编写 API 完成 HDFS shell 操作
- 微信小程序-入门篇(app.wxml及app.wxss)
- 13.9-全栈Java笔记:打飞机游戏实战项目|Time|Plane|其他案例展示
- HTML5_DOM-有缝-透明度-无缝-封装
- 机器学习实战_初识决策树算法_理解其python代码(一)
- 在Intellij IDEA 关于git的一些用法
- XZ_iOS之自定义2秒钟自动消失的提示框
- 小团队服务器开发