博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
230. Kth Smallest Element in a BST
阅读量:4641 次
发布时间:2019-06-09

本文共 1223 字,大约阅读时间需要 4 分钟。

题目:

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:

    1. Try to utilize the property of a BST.
    2. What if you could modify the BST node's structure?
    3. The optimal runtime complexity is O(height of BST).

链接:  

7/25/2017

2ms, 20%

好几天终于有道自己做的题了。。。iterative inorder traversal

1 public class Solution { 2     public int kthSmallest(TreeNode root, int k) { 3         Stack
stack = new Stack<>(); 4 TreeNode node = root; 5 int kthSml = 0; 6 7 while((node != null || !stack.isEmpty()) && k > 0) { 8 while (node != null) { 9 stack.push(node);10 node = node.left;11 }12 node = stack.pop();13 kthSml = node.val;14 k--;15 node = node.right;16 }17 return kthSml;18 }19 }

别人的答案

可以利用DFS求root的count,然后再从左右两边找

python generator

r

更多讨论

转载于:https://www.cnblogs.com/panini/p/7236107.html

你可能感兴趣的文章
ASP.NET MVC Identity 兩個多個連接字符串問題解決一例
查看>>
过滤器与拦截器区别
查看>>
USACO 1.5.4 Checker Challenge
查看>>
第二阶段站立会议7
查看>>
[18]Debian Linux Install GNU GCC Compiler and Development Environment
查看>>
JAVA多线程
查看>>
ACE(Adaptive Communication Environment)介绍
查看>>
delphi 更改DBGrid 颜色技巧
查看>>
python编码问题
查看>>
POJ 2031 Building a Space Station
查看>>
面向对象1
查看>>
编程开发之--java多线程学习总结(5)
查看>>
register_globals(全局变量注册开关)
查看>>
as3调用外部swf里的类的方法
查看>>
如何让 zend studio 10 识别 Phalcon语法并且进行语法提示
查看>>
任意阶幻方(魔方矩阵)C语言实现
查看>>
视频教程--ASP.NET MVC 使用 Petapoco 微型ORM框架+NpgSql驱动连接 PostgreSQL数据库
查看>>
第五次作业
查看>>
织梦教程
查看>>
杭电多校 Harvest of Apples 莫队
查看>>