230. Kth Smallest Element in a BST
Problem
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?
题目大意
写一个函数kthSmallest,实现从一个给定的二叉排序树中查找第k个小的元素。
提示:
默认k总是合法的输入(1≤k≤二叉排序树结点总数)
跟进:
当二叉排序树经常被修改(插入/删除)时,如何快速找到第k小的数?如何优化?
思路
此题目考察的依旧是二叉树的遍历。
1. 根节点进栈,左子树根节点依次进展直到最左端叶子节点。
2. 栈顶元素出栈。
3. 判断出栈元素是否有右子树,若有,回到步骤(1),否则,继续。
4. 判断是第几个元素出栈,若是第k个,则结束,返回该元素的值。若小于k,则回到步骤(2)。
代码实现–Java
/**
* 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 stack = new Stack();
while (root != null) {
stack.push(root);
root = root.left;
}
while(k >0){
k--;
root = (TreeNode)stack.pop();
TreeNode node = root.right;
while(node != null) {
stack.push(node);
node = node.left;
}
}
return root.val;
}
}
运行结果
结果分析
代码虽然可以通过,但是效率并不高,还需要进一步优化。