Kth Smallest Element in a BST
2015-07-15 16:33
239 查看
Given a binary search tree, write a function
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?
kthSmallestto 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?
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private int n = 0; private TreeNode re_node; //中序遍历二叉排序树 public void InOrderTravel(TreeNode root,int k) { if(root!=null) { InOrderTravel(root.left,k); n++; if(n==k) { this.re_node = root; return; } InOrderTravel(root.right,k); } } public int kthSmallest(TreeNode root, int k) { InOrderTravel(root,k); return this.re_node.val; } }
相关文章推荐
- Sublime Text 2 超实用插件与快捷键
- platform详解
- 初学者如何查阅自然语言处理(NLP)领域学术资料
- JPush推送整理总结
- 1011. World Cup Betting (20)
- Geometry cannot have Z values
- struts1源码分析(三)请求处理主线
- Burp Suite安装及详细使用教程-Intruder模块详解
- 在PPT中插入并嵌入SWF文件图文教程
- android保存图片到本地sd卡
- Burp Suite安装及详细使用教程-Intruder模块详解
- test
- linux中如何修改文件夹的用户权限 chown命令
- 【转】深入理解Java的接口和抽象类
- window 下 利用gradle编译volley源代码
- PowerDesign连接mysql数据库
- 车轮碰撞体(wheelcollider)
- 解决 TinyXML中文乱码的问题
- Apache Jmeter压力测试神器-快速入门
- 嵌入Linux开发环境搭建--secruceCRT配置