230. Kth Smallest Element in a BST
来源:互联网 发布:周杰伦 忍者 知乎 编辑:程序博客网 时间:2024/05/22 17:42
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?
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int kthSmallest(TreeNode root, int k) { Stack<TreeNode> data = new Stack<TreeNode>();while (root != null || !data.isEmpty()) {while (root != null) {data.push(root);root = root.left;}root = data.pop();k--;if (k == 0)return root.val;root = root.right;}return -1; }}
0 0
- 230.Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- CF 787D 线段树套堆优化Dij
- [翻译] Emacs改变了我的人生 (发生在Emacs和Ruby之间的故事)
- 【运维管理】IT管理员常用的管理、运维工具有哪些?
- 字符串算法系列-LeetCode#5.LongestPalindromicSubstring
- 输出100~999中所有的水仙花数
- 230. Kth Smallest Element in a BST
- mac 下安装memcache扩展
- 机器学习中的相似性度量 (多种几何距离定义)
- Apk 反编译 重新打包 工具及命令
- struts2拦截器介绍
- DataContractJsonSerializer 找不到命名空间
- org.springframework.web.multipart.MultipartException: The current request is not a multipart request
- gdb调试器的相关命令
- 配置小程序的艰辛历程